@Value와 PropertySourcesPlaceholderConfigurer
@MyAutoConfiguration
@ConditionalMyOnClass("org.apache.catalina.startup.Tomcat")
public class TomcatWebServerConfig {
@Value("${contextPath}")
String contextPath;
@Bean("tomcatWebServerFactory")
public ServletWebServerFactory servletWebServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.setContextPath(this.contextPath);
return factory;
}
}
application.properties의 환경변수를 필드로 주입받기 위해서는 @Value 애노테이션을 사용하면 주입받을 수 있습니다. 다만 위 설정만 하고 Application run을 하면 오류가 발생합니다. 왜냐하면 빈 생성수 후처리작읍을 해야할 bean을 설정해주지 않았기 때문에 아무리 @Value애노테이션을 설정하였다 하더라도 application.properties의 설정한 값이 주입되지 않고 @Value애노테이션에 설정한 값이 그대로 출력됩니다.
@MyAutoConfiguration
public class PropertyPlaceholderConfig {
@Bean
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
따라서 자동구성정보의 후처리를 담당할 PropertySourcesPlaceholderConfigurer bean을 등록해 줍니다.
com.tobyspring.config.MyAutoConfiguration.imports
com.tobyspring.config.autoconfig.PropertyPlaceholderConfig
자동 구성정보를 추가하기때문에 Spring이 인지할 수 있도록 imports파일에 해당 PropertySourcesPlaceholderConfigurer를 등록해 줍니다.
'Spring > 인프런 토비의 Spring Boot' 카테고리의 다른 글
섹션 8-4 [외부 설정을 이용한 자동 구성] 프로퍼티 클래스의 분리 (0) | 2024.07.26 |
---|---|
섹션 8-2 [외부 설정을 이용한 자동 구성] 자동 구성에 Enviroment 프로퍼티 적용 (0) | 2024.07.26 |
섹션 8-1 [외부 설정을 이용한 자동 구성] Enviroment 추상화와 프로퍼티 (0) | 2024.07.26 |
섹션 7-6 [조건부 자동구성] 스프링 부트의 @Conditional (0) | 2024.06.27 |
섹션 7-5 [조건부 자동구성] 자동 구성 정보 대체하기 (0) | 2024.06.27 |