.properties파일 대신 .yml파일을 사용할 수 있다.
어떻게? classpath에 SnakeYAML Library가 있으면 사용할 수 있다. 그런데 spring-boot-starter가 있으면 자동으로 제공해준다. 따라서 .yml파일을 사용할 수 있다.
- 내부적으로 결국에는 yaml파일을 properties파일로 변환한다.
server: port: 8000 --- spring: profiles: default server: port: 8080
- 이렇게 생성한다면 spring.profiles는 기본적으로 "default"로 설정되어있어 server port는 8080이 된다.
@Component @ConfigurationProperties("acme") public class AcmeProperties { private boolean enabled; private InetAddress remoteAddress; }
이렇게 되어있으면 acme.enabled와 acme.remoteAddress가 Type에 맞게 바인딩 된다.(좋은데유?)
단 getter, setter, default empty생성자가 필수로 필요하다.
lombok을 사용하는 경우 빈생성자가 아닌 아규먼트를 가진 생성자를 생성하는 경우가 있는데, 이러면 자동으로 그걸 사용하게 되므로 주의하자.
의문점.. 그러면 argument이름을 읽어와서 자동주입을 해준다구?...안된대요. 즉 lombok하면 안되요... 이러면 다른생성자 생기게될 수 있어서 ㅠ헐.... Reference를 읽다가 알게된 바뀐 내용!
@ConstructBinding을 이용하게되면 Immutable하게 관리를 할 수 있게된다. 위에서는 Setter를 통해서 언제든 바뀔 수 있는 mutable이지만 ConstructorBinding을 하게되면 빈생성자가아닌 get과 allArgsConstructor를 통해 설정을 하기 때문에 immutable하게 관리가 가능하다. 그리고 만약 값이 없는경우에는?..acme.enabled가 없으면은..?
@DefaultValue annotation을 통해 default값 설정이 가능하다.그리고 @EnableConfigurationProperties( AcmeProperties::class)를 main에다가 붙여줘야한다. 왜냐하면 ConfigurationProperties의 scanning방식이 disable되기 때문이다.
즉!! 결론은!!!
@ConstructorBinding @ConfigurationProperties("acme") @Getter public class AcmeProperties { private final boolean enabled; private final InetAddress remoteAddress; private final Security security; public AcmeProperties(boolean enabled, InetAddress remoteAddress, @DefaultValue Security security) { this.enabled = enabled; this.remoteAddress = remoteAddress; this.security = security; } } @EnableConfigurationProperties( AcmeProperties::class) public class MainApplication { }
위와 같이 사용해야 한다.
- @EnableConfigurationProperties? 프로퍼티클래스를 빈으로 등록해줌.