Spring
@ConfigurationProperties 사용해보기
junseokoh
2021. 5. 18. 15:10
Annotation Processor를 사용해서 Metadata 생성하기
Configuration Metadata
Configuration metadata files are located inside jars under META-INF/spring-configuration-metadata.json. They use a JSON format with items categorized under either “groups” or “properties” and additional values hints categorized under "hints", as sh
docs.spring.io
Annotation Processor 구성
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
ServerProperties.java
@ConfigurationProperties(prefix = "server")
public class ServerProperties {
/**
* Name of the server.
*/
private String name;
/**
* IP address to listen to.
*/
private String ip;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
getter/setter를 통해 속성이 검색되고 lombok의 @Data, @Getter, @Setter 도 지원 합니다.
위와 같이 @ConfigurationProperties를 설정하게 되면 application.yml(application.properties) 에서 값을 설정할 수 있습니다.
application.yml
server:
name: app
ip: 127.0.0.1
ServerConfiguration.java
@Configuration
@EnableConfigurationProperties(ServerProperties.class)
public class ServerConfiguration {
@Bean
public DummyServer dummyServer(ServerProperties properties) {
DummyServer dummyServer = new DummyServer();
dummyServer.setName(properties.getIp());
dummyServer.setIp(properties.getIp());
return dummyServer;
}
}
@EnableConfigurationProperties 를 붙이게 되면 properties에는 application 설정파일에서 설정한 값이 들어오게 됩니다.
그렇게 되면 java코드에 설정값을 하드코딩하지 않고 사용할 수 있습니다.