@Service
public class UserService {
private final UserRepository userRepository;
// 생성자를 통해 의존성 주입
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
final 사용 가능 → 불변 보장@Autowired 생략 가능@Service
public class UserService {
@Autowired
private UserRepository userRepository;
}
@Service
public class UserService {
private UserRepository userRepository;
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
@RequiredArgsConstructor
@Service
public class UserService {
private final UserRepository userRepository;
}
final 필드만 대상으로 생성자 자동 생성코드에서 의존성 선언 → 스프링이 Bean 생성 및 주입 → 주입된 객체 사용
이 흐름에서 @Configuration과 @Bean은 "어떻게 의존 객체(Bean)를 만들지"를 정의하는 핵심 역할을 합니다.
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserService(userRepository());
}
@Bean
public UserRepository userRepository() {
return new UserRepositoryImpl();
}
}
이 클래스는 스프링 컨테이너가 Bean을 등록하는 팩토리 역할을 합니다.
@Configuration은 내부적으로 프록시 기반의 싱글톤 보장 기능을 제공@Bean 메서드 간 호출 시에도 중복 객체가 생성되지 않음@Bean
public UserService userService() {
return new UserService(userRepository());
}
@Bean메서드는 수동 등록된 Bean을 의미합니다.
스프링 컨테이너는 이 메서드가 반환하는 객체를 Bean으로 등록하고 DI 대상에 주입해줍니다.
@Service
@RequiredArgsConstructor
public class OrderService {
private final PaymentService paymentService;
}
@Configuration
public class PaymentConfig {
@Bean
public PaymentService paymentService() {
return new KakaoPayService();
}
}
스프링이
OrderService를 생성할 때,PaymentService타입의 Bean을 찾아
paymentService()메서드가 반환하는 객체를 주입합니다.
스프링 컨테이너가 Bean을 생성할 때, 필요한 의존성을 찾아서 넣어줌
Bean은 기본적으로 싱글톤이라 서버 전체에서 재사용
| 어노테이션 | 설명 |
|---|---|
@Component | 일반적인 컴포넌트 등록 |
@Service | 서비스 레이어 등록 |
@Repository | DB 레이어 등록 + 예외 변환 |
@Controller / @RestController | 웹 요청 처리 |