반응형
1. 타입 세이프 프로퍼티 @ConfigurationProperties
- 여러 프로퍼티들을 묶어서 읽어올 수 있음
- @AutoWired 로 간단하게 가져올 수 있음
- @Value 보다는 @ConfigurationProperties 로 쓰는게 나음
package com.example.springapplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("naeun")
public class NaeunProperties {
String name;
int age;
String fullName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
}
NaeunProperties.java
-> 새로운 파일 생성
-> @Component로 빈으로 등록해주기
-> @ConfigurationProperties 로 이름붙여주기?
@Component
public class SampleRunner implements ApplicationRunner {
@Autowired
NaeunProperties naeunProperties;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("====================");
System.out.println(naeunProperties.getName());
System.out.println(naeunProperties.getAge());
System.out.println("====================");
}
}
SampleRunner.java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
의존성 추가
-> 메타정보를 생성해주는 의존성 추가, 자동완성 사용가능
2. 프로퍼티 타입 컨버젼
application.properties 에 적은 문자열이
int형으로 선언하면 int 형으로 자동으로 타입이 바뀜
application.properties 에 적은 문자열이
Duration형으로 선언하면 Duration 형으로 자동으로 타입이 바뀜
3. 검증
@Component
@ConfigurationProperties("naeun")
@Validated
public class NaeunProperties {
@NotEmpty
String name;
int age;
String fullName;
@DurationUnit(ChronoUnit.SECONDS)
private Duration sessionTimeout = Duration.ofSeconds(30);
public Duration getSessionTimeout() {
return sessionTimeout;
}
public void setSessionTimeout(Duration sessionTimeout) {
this.sessionTimeout = sessionTimeout;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
}
-> @Validated, @NotEmpty 사용해서 값이 없으면 오류가 나게 함
반응형
'Programming > Spring' 카테고리의 다른 글
활용 6) 로깅(logging) 커스터마이징 (0) | 2020.10.11 |
---|---|
활용 5) 프로파일(profile) (0) | 2020.10.11 |
활용 3) 외부설정 : application.properties (0) | 2020.10.11 |
기초 1) 스프링 빈(Bean) (0) | 2020.10.10 |
활용 2) SpringApplication 2 : 이벤트 리스너, ApplicationArguments (0) | 2020.10.10 |