0720 Spring 복습 정리
✅ 1. 인터페이스와 의존성 주입 기본 개념 (0714)
🔹 인터페이스 기반 설계
- 객체 간의 결합도를 낮추기 위해 인터페이스를 활용.
- 다형성을 활용해 다양한 구현체를 교체하기 쉽게 만듦.
public interface Chef {
void cook();
}
🔹 의존성 주입(DI: Dependency Injection)
- 직접 객체 생성 없이 외부에서 객체를 주입받아 사용하는 설계.
- 유지보수, 테스트, 확장성이 좋아짐.
🔹 DI 방식
✅ 2. @Configuration, @Bean을 이용한 Java 기반 설정 (0715)
🔸 @Configuration
🔸 @Bean
- 해당 메서드의 리턴 객체를 스프링 빈으로 등록.
@Configuration
public class AppConfig {
@Bean
public Car car() {
return new Car(engine());
}
@Bean
public Engine engine() {
return new Engine();
}
}
🧪 테스트 코드 작성법
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Car car = context.getBean(Car.class);
car.drive();
✅ 3. @Component 기반 스캔 방식 (0716)
🔸 주요 어노테이션
@Component: 일반 컴포넌트 등록
@Controller, @Service, @Repository: 특화된 컴포넌트 (@Component의 확장)
🔸 자동 빈 등록
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {}
🔸 생성자 주입 + @Autowired
@Controller
public class MyController {
private final MyService myService;
@Autowired
public MyController(MyService myService) {
this.myService = myService;
}
}
✅ 4. Feed 게시판 예제 구조 (0717)
🔹 구성 요소
- Controller: 요청 처리
- Service: 비즈니스 로직 처리
- Repository: 저장소 역할 (메모리 기반)
- DTO: 요청/응답 전용 객체 분리
🔹 컨트롤러 기능 예시
- GET
/feeds - 전체 피드 조회
- POST
/feeds - 피드 등록
- GET
/feeds/{id} - 피드 개별 조회
- DELETE
/feeds/{id} - 피드 삭제
✅ 5. 롬복(Lombok) + Qualifier 사용 (0718)
🔸 롬복 어노테이션
@Getter, @Setter, @ToString, @AllArgsConstructor, @NoArgsConstructor, @Builder
- DTO, Entity 클래스의 보일러플레이트 코드를 줄여줌.
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Feed {
private Long feedId;
private String content;
private String writer;
private LocalDateTime createdAt;
private int viewCount;
}
🔸 @Qualifier
- 같은 타입의 빈이 여러 개일 때 어떤 빈을 주입할지 명시
@Autowired
public StudentController(@Qualifier("smr") StudentRepository repository) {
this.repository = repository;
}
📌 요약 정리
- 인터페이스 기반 설계는 결합도를 낮추고 유연한 구조 설계에 필수.
- DI(의존성 주입)를 통해 객체 생성 책임을 스프링 컨테이너에 위임.
- Java 기반 설정은
@Configuration + @Bean,
- 어노테이션 기반 설정은
@Component, @Service, @Controller 등을 사용.
- Feed 게시판 예제를 통해 스프링 MVC 계층 구조 이해.
- 롬복과 @Qualifier는 코드 간결성과 명확한 빈 주입에 도움을 줌.