[Spring] Multiple YML(Constants) 파일 관리
현재 많은 프로젝트들을 환경값을 application.properties 파일에서 application.yml파일로 관리를 하고 있다.
이렇게 되면서 Constants 역시 기존에는 class파일에서 yml파일로 관리를 하는 경우가 생겼고,
application.yml에서 물론 전부 관리할 수 있지만 별도의 yml파일로 분리하여 관리하여할 경우가 있어서, 해당 방법을 알아보자
기존의 application.yml은
@Configuration
public class CustomConfig {
public CustomConfig(@Value("${info.name}") String name){
//use Your Constants
}
}
이와 같은 방식으로 사용할 수 있었다.
1. resoures/constants.yml 생성
info :
code : abc123
key : afhjsd13
resoures 폴더 아래에 constants 정리한 yml 파일을 생성한다.
2. PropertySourceFactory 생성
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) {
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
YamlPropertySourceFactory : 지정한 classpath로 지정한 resource 파일을 Property값들이 저장된 Map으로 만들어 value를 가져올 수 있게 한다.
3. Configuration Class에 classPath설정
@Configuration
@PropertySource(value = "classpath:constants.yml",
factory = YamlPropertySourceFactory.class, ignoreResourceNotFound = true)
public class CustomConfig {
public class CumstomConfig(@Value("${info.code}") String code){
//use code value
}
}
@PropertySource를 추가하여 필요한 yml파일을 지정해주고, 아까 생성한 YamlPropertySourceFactory을 factory에 등록한다. 만약 yml 파일이 아닌 properties 파일을 추가할 경우에는 factory를 등록하지않고 사용하면 된다.
ignoreResourceNotFound는 지정한 resource 파일을 찾을 수 없을 경우 에러를 발생여부를 지정할 수 있다.
이렇게 되면 Constructor 뿐만 아니라 @Bean에서도 @Value를 바로 받아 사용할 수 있다.
(추가) 여러개의 resource 파일이 필요할 경우
@PropertySource(value = {"classpath:constants.yml", "classpath:constants1.yml",
"classpath:constants3.yml"}, factory =.....)
public class CustomConfig{
}
value에 array 형태로 다중 resource 파일을 등록할 수 있다.