공부/Tools
[SpringBoot] YamlPropertySourceFactory 기록
aerhergag0
2024. 2. 28. 19:23
- 클래스 설정
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(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;
}
}
}
- application.yml
spring:
profiles:
active: key
- application-key.yml (.ignore에 추가할것)
jwt:
secretKey: {}
spring:
datasource:
url: {}
driver-class-name: {}
username: {}
password: {}
- 적용 및 설정
@PropertySource(value = "classpath:application-key.yml", factory = YamlPropertySourceFactory.class, ignoreResourceNotFound = true)
public class JwtService {
@Value("${jwt.secret-key}")
private String secretKey;
...