본문 바로가기

Backend Development/Spring boot

[Spring boot] @ConfigurationProperties 사용하기

@ConfigurationProperties 는 Spring Boot 에서 application.properties 파일에 정의된 프로퍼티들을 POJO 에 매핑하여 Bean 으로 만들수 있게 해주는 어노테이션이다.

 

아래의 application.properties에 정의된 값들을 Pojo제 받기 위해 ConfugurationProperties를 작성한다.

 

application-dev.properties

 

app.auth.tokenSecret=04ca023b39512e46d0c2cf4b48d5aac61d34302994c87ed4eff225dcf3b0a218739f3897051a057f9b846a69ea2927a587044164b7bae5e1306219d50b588cb1
app.auth.tokenExpirationMsec=864000000

 

@ConfigurationProperties(prefix = "app")
public class AppProperties {
    private final Auth auth = new Auth();
    private final OAuth2 oauth2 = new OAuth2();

    public static class Auth {
        private String tokenSecret;
        private long tokenExpirationMsec;

        public String getTokenSecret() {
            return tokenSecret;
        }

        public void setTokenSecret(String tokenSecret) {
            this.tokenSecret = tokenSecret;
        }

        public long getTokenExpirationMsec() {
            return tokenExpirationMsec;
        }

        public void setTokenExpirationMsec(long tokenExpirationMsec) {
            this.tokenExpirationMsec = tokenExpirationMsec;
        }
    }

    public static final class OAuth2 {
        private List<String> authorizedRedirectUris = new ArrayList<>();

        public List<String> getAuthorizedRedirectUris() {
            return authorizedRedirectUris;
        }

        public OAuth2 authorizedRedirectUris(List<String> authorizedRedirectUris) {
            this.authorizedRedirectUris = authorizedRedirectUris;
            return this;
        }
    }

    public Auth getAuth() {
        return auth;
    }

    public OAuth2 getOauth2() {
        return oauth2;
    }
}

 

com/sdp/SdpApplication.java

 

@EnableConfigurationProperties(AppProperties.class)
@SpringBootApplication
public class SdpApplication extends SpringBootServletInitializer implements WebApplicationInitializer {

   @Bean
   public HttpSessionListener httpSessionListener(){
      return new SessionListener();
   }

   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
      return application.sources(SdpApplication.class);
   }

   public static void main(String[] args) {
      SpringApplication.run(SdpApplication.class, args);
   }

}

 

스프링이 Bean 을 application context 에 만들도록 @Configuration을 property class에 붙여주거나 
main Spring application 클래스에 @EnableConfigurationProperties(ConfigProperties.class) 를 붙여준다.

 

 

Property 유효성 검사

아래와 같이 빈 문자열 검사, 문자열 길이 범위, 정수 범위, 정규표현식을 통한 문자열의 형태를 체크할 수 있다.

 

@NotBlank
private String hostName;

@Length(max = 4, min = 1)
private String authMethod;

@Min(1025)
@Max(65536)
private int port;

@Pattern(regexp = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,6}$")
private String from;

만약 유효성 검사가 실패하면 IllegalStateException 이 발생하여 main application 의 실행이 실패한다.

 

 

application.properties 값 설정

 

application.properties에 설정된 값 중 server.xx 로 시작되는 값은 아래 소스에서 자동 맵핑하게 되어있다. @ConfigurationProperties 어노테이션이 붙어 있는것을 볼 수 있다.

 

org/springframework/boot/spring-boot-autoconfigure/2.5.6/spring-boot-autoconfigure-2.5.6-sources.jar!/org/springframework/boot/autoconfigure/web/ServerProperties.java:74

 

@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {

	/**
	 * Server HTTP port.
	 */
	private Integer port;

	/**
	 * Network address to which the server should bind.
	 */
	private InetAddress address;

	@NestedConfigurationProperty
	private final ErrorProperties error = new ErrorProperties();

	/**
	 * Strategy for handling X-Forwarded-* headers.
	 */
	private ForwardHeadersStrategy forwardHeadersStrategy;

	/**
	 * Value to use for the Server response header (if empty, no header is sent).
	 */
	private String serverHeader;

	/**
	 * Maximum size of the HTTP message header.
	 */
	private DataSize maxHttpHeaderSize = DataSize.ofKilobytes(8);

	/**
	 * Type of shutdown that the server will support.
	 */
	private Shutdown shutdown = Shutdown.IMMEDIATE;

	@NestedConfigurationProperty
	private Ssl ssl;

	@NestedConfigurationProperty
	private final Compression compression = new Compression();

	@NestedConfigurationProperty
	private final Http2 http2 = new Http2();

	private final Servlet servlet = new Servlet();

	private final Tomcat tomcat = new Tomcat();

	private final Jetty jetty = new Jetty();

	private final Netty netty = new Netty();

	private final Undertow undertow = new Undertow();