@Value값 디폴트 설정하기
@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;
}
}
@Value값에 ${contextPath} applicatio.propertes의 명을 기입하지만 만약 설정된 환경변수가 존재하지 않는다면 디폴트값으로 / 가 contextPath값으로 설정되도록 하고싶다면 간단하게 contextPath:/으로 설정하면 됩니다.
프로퍼티 클래스의 분리
@MyAutoConfiguration
@ConditionalMyOnClass("org.apache.catalina.startup.Tomcat")
public class TomcatWebServerConfig {
@Value("${contextPath:/}")
String contextPath;
@Bean("tomcatWebServerFactory")
public ServletWebServerFactory servletWebServerFactory(ServiceProperties serviceProperties) {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.setContextPath(serviceProperties.getContextPath());
factory.setPort(serviceProperties.getPort());
return factory;
}
}
public class ServiceProperties {
private String contextPath;
private int port;
public String getContextPath() {
return contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
@MyAutoConfiguration
public class ServicePropertiesConfig {
@Bean
ServiceProperties serviceProperties(Environment environment) {
return Binder.get(environment).bind("", ServiceProperties.class).get();
}
}
com.tobyspring.config.MyAutoConfiguration.imports
com.tobyspring.config.autoconfig.ServicePropertiesConfig
enviroment에서 하나한 getPropertues하지않고 Properties Class를 구성하여 Spring Boot가 제공하는 Binder를 통해서 application.properties의 값을 객체로 바인딩할 수 있게 됩니다. 이를 관리에 용이성이 증가하게 됩니다.
'Spring > 인프런 토비의 Spring Boot' 카테고리의 다른 글
섹션 8-3 [외부 설정을 이용한 자동 구성] @Value와 PropertySourcesPlaceholderConfigurer (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 |