@Component 계열(Component Scan 기반)
클래스에 어노테이션 붙이면 자동으로 Bean 등록된다.
@CompoentScan이 스캔하여 Bean으로 등록한다.
- @Component
- @Service
- @Repository
- @Controller
- @RestCtontroller
- 등등
@Component
public class MyService {
// ...
}
@Service
public class UserService {
// ...
}
@Repository
public class UserRepository {
// ...
}
@Controller
public class UserController {
// ...
}
| 장점 | 단점 |
| 코드 간결 | Bean 생성과정 커스텀 어려움 |
| 컴포넌트 스캔으로 자동 등록되어 편리 | |
| 유지보수 쉬움 | 외부 라이브러리 클래스에는 사용 불가 |
@Bean(Java Config 방식)
설정 클래스 안에서 직접 Bean 생성
@Configuration
public class AppConfig {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
}
- return 되는것이 Bean으로 등록된다.
- 외부 라이브러리 Bean 등록 가능
- 커스텀 가능
- 코드 증가
- 설정 클래스 비대해질 수 있음.
@Import
@ConfigurationProperties + Bean 등록
@ConfigurationProperties: 설정파일의 값들을 객체로 자동매핑해주는 어노테이션.
[기존 방식]
@Service
public class EmailService {
@Value("${email.host}")
private String host;
@Value("${email.port}")
private int port;
@Value("${email.username}")
private String username;
@Value("${email.password}")
private String password;
// 설정이 많아질수록 코드가 지저분해짐
}
[@ConfigurationProperties 방식]
@ConfigurationProperties(prefix = "email")
public class EmailProperties {
private String host;
private int port;
private String username;
private String password;
// getter, setter
}
# application.properties
email.host=smtp.gmail.com
email.port=587
email.username=myemail@gmail.com
email.password=secret123
- 훨씬 깔끔하다.
[Bean 등록방법]
1.@Component
@Component
@ConfigurationProperties(prefix = "app.database")
public class DatabaseProperties {
private String url;
private String username;
private String password;
private int maxConnections;
// getter, setter 필수!
}
# application.properties
app.database.url=jdbc:mysql://localhost:3306/mydb
app.database.username=root
app.database.password=1234
app.database.max-connections=10
- max-connections -> maxConnections로 자동변환
- Spring이 setter로 값 주입하기때문에 getter/setter 반드시 필요.
2.@ConfigurationPropertiesScan 사용
// 1. Properties 클래스들
@ConfigurationProperties(prefix = "app.email")
public class EmailProperties {
private String host;
private int port;
// getter, setter
}
@ConfigurationProperties(prefix = "app.sms")
public class SmsProperties {
private String apiKey;
private String sender;
// getter, setter
}
// 2. Application 클래스에서 자동 스캔
@SpringBootApplication
@ConfigurationPropertiesScan // 모든 @ConfigurationProperties를 자동으로 Bean 등록
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
// 또는 특정 패키지만 스캔
@SpringBootApplication
@ConfigurationPropertiesScan("com.example.config.properties")
public class Application {
// ...
}
조건부 Bean(@Conditional 계열)
- @ConditionalOnProperty
- @ConditionalOnMissingBean
- @ConditionalOnClass
- 등등
@Configuration //이 클래스는 Bean 설정 파일이다.
public class ConditionalConfig {
@Bean
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
//application.properties 파일에 feature.enabled=true가 있으면 FeatureService Bean 등록
public FeatureService featureService() {
return new FeatureService();
}
@Bean
@ConditionalOnMissingBean //DefaultService타입의 Bean이 없으면, Bean으로 등록
public DefaultService defaultService() {
return new DefaultService();
}
@Bean
@Profile("dev")// dev 프로파일이 활성화 되어 있을때만 H2DataSource Bean등록
public DataSource devDataSource() {
return new H2DataSource();
}
}
- 조건에따라 Bean을 동적으로 등록할 수 있다.
- 환경별 설정을 유연하게 관리할 수 있다.
- 조건이 복잡해지면 디버깅이 어렵다.
XML Bean 등록(거의 사용 x)
- 레거시 Spring 방식
| 방법 | 사용 난이도 | 유연성 | 외부라이브러리 | 초기화 제어 | 조건부 등록 | 주요 용도 |
| @Component 계열 | 매우 쉬움 | 낮음 | 불가능 | 제한적 | 어려움 | 일반 클래스 |
| @Configuration + @Bean | 쉬움 | 매우 높음 | 가능 | 완전 제어 | 쉬움 | 외부 라이브러리, 복잡한 설정 |
| @ConfigurationProperties | 보통 | 보통 | 가능 | 보통 | 보통 | 설정값 바인딩 |
| @Import | 어려움 | 높음 | 가능 | 높음 | 매우 쉬움 | 모듈화, 라이브러리 제작 |
| @ComponentScan | 쉬움 | 보통 | 불가능 | 제한적 | 보통 | 패키지 단위 자동 등록 |
| @Conditional 계열 | 보통 | 매우 높음 | 가능 | 높음 | 매우 쉬움 | 조건부 Bean 등록 |
| FactoryBean | 매우 어려움 | 매우 높음 | 가능 | 완전 제어 | 보통 | 프록시, 복잡한 생성 로직 |
'위클리페이퍼' 카테고리의 다른 글
| GitHub Actions Trigger 유형과 CI/CD 활용 시나리오 (0) | 2026.05.15 |
|---|---|
| AWS RDS를 활용하는 이점과 EC2에 직접 DB 설치 비교 (0) | 2026.05.12 |
| Spring MVC에서 클라이언트의 요청 처리 흐름.(@Controller/@RestController) (0) | 2026.02.23 |
| 웹 서버와 WAS(Web Application Server)의 차이 (0) | 2026.02.02 |
| 프레임워크와 라이브러리의 차이점? (0) | 2026.01.27 |