- 아래 출처 글을 바탕으로 작성하였습니다.
- 개인 공부 목적으로 작성한 글입니다.
1. 사용하는 이유
@EnableConfigurationProperties
는 @ConfigurationProperties
클래스를 Bean으로 등록하여 쓸 때(주입받을 때) 사용합니다.
2. 예시 코드 1
- 먼저 configuration 클래스(
@ConfigurationProperties
)를 정의합니다.
@ConfigurationProperties(prefix = "additional")
public class AdditionalProperties {
private String unit;
private int max;
}
@EnableConfigurationProperties
을 사용합니다.
@EnableConfigurationProperties
사용하면 configuration 클래스를 bean으로 등록할 수 있습니다.
- 그러면 이제 다른 Spring 빈처럼
AdditionalProperties
를 사용할 수 있습니다.
- 예시코드에서는
Autowired
를 통해 주입받았습니다.
@Configuration
@EnableConfigurationProperties(AdditionalProperties.class)
public class AdditionalConfiguration {
@Autowired
private AdditionalProperties additionalProperties;
}
3. 예시 코드 2
- 먼저 configuration 클래스(
@ConfigurationProperties
)를 정의합니다.
@ConfigurationProperties("service")
public class ServiceProperties {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
@EnableConfigurationProperties
을 사용합니다.
@EnableConfigurationProperties
사용하면 configuration 클래스를 bean으로 등록할 수 있습니다.
- 그러면 이제 다른 Spring 빈처럼
ServiceProperties
를 사용할 수 있습니다.
@Service
@EnableConfigurationProperties(ServiceProperties.class)
public class MyService {
private final ServiceProperties serviceProperties;
public MyService(ServiceProperties serviceProperties) {
this.serviceProperties = serviceProperties;
}
public String message() {
return this.serviceProperties.getMessage();
}
}