본문 바로가기
Spring/인프런 토비의 Spring Boot

섹션 8-4 [외부 설정을 이용한 자동 구성] 프로퍼티 클래스의 분리

by include_hoany 2024. 7. 26.

@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의 값을 객체로 바인딩할 수 있게 됩니다. 이를 관리에 용이성이 증가하게 됩니다.