-
@ConfigurationProperties 사용해보기Spring 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코드에 설정값을 하드코딩하지 않고 사용할 수 있습니다.
'Spring' 카테고리의 다른 글
프로젝트 회고 - 수업 스케줄 일괄 변경 배치 처리 (0) 2024.04.08 프로젝트 회고 - 스케줄 자동 공개 성능 최적화 (1) 2024.04.04 Spring Version에 맞는 h2Database 설치 (0) 2023.04.16 @Transactional 제대로 알고 쓰기 (0) 2021.11.18 web.xml 에 선언된 context-param, init-param 테스트 (0) 2021.06.30