코딩마을방범대

yml 정보 클래스로 가져오기 본문

💡 백엔드/Java

yml 정보 클래스로 가져오기

신짱구 5세 2023. 5. 26. 09:37
728x90

참고


application.yml에서 가져오기

1. yml에 필요한 정보 기입


  
aes:
key: "secreyKey"

 

2. build.gradle에 dependency 추가


  
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"

 

3. yml 정보를 가져다 쓸 클래스 생성

  • getter, setter가 필요하므로 Data 어노테이션으로 대체
  • @Configuration 적용이 필요함
  • @ConfigurationProperties의 prefix에 그룹변수명 기입

  
@Configuration
@Data
@ConfigurationProperties(prefix = "aes")
public class ApplicationSetting {
private String key;
}

 

4. 사용하기


  
@Component
@RequiredArgsConstructor
public class AES256 {
private final ApplicationSetting applicationSetting;





별도 yml에서 가져오기

1,2 번은 동일하게 세팅

1. factory 생성

PropertySource에 yml을 read할 수 있는 factory가 없기 때문에 임의로 생성


  
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}

2. yml 정보를 가져다 쓸 클래스 생성


  
@Configuration
@Data
@PropertySource(value = "classpath:aes.yml", factory = YamlPropertySourceFactory.class)
@ConfigurationProperties(prefix = "aes")
public class ApplicationSetting {
private String key;
}

 

사용은 위와 동일하게 사용!

728x90

'💡 백엔드 > Java' 카테고리의 다른 글

Entity에서 암복호화 & JAVA 비동기 처리(Thread)  (0) 2023.05.26
Java로 메일 발송하기  (0) 2023.05.26
SHA-256 해싱 알고리즘  (0) 2023.05.26
JAVA에서의 암호화 방법 (AES)  (0) 2023.05.26
ModelMapper란  (0) 2023.05.25