Spring Boot 게시판 만들기 18 - 외부로부터 설정 받기(yml)

18. 외부로부터 설정 받기(yml)

YamlPropertySourceFactory.java

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) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();

if (cause instanceof FileNotFoundException) {
throw (FileNotFoundException) e.getCause();
}
throw e;
}
}
}

DBConfigByYml.java

@Configuration
@PropertySource(value = "classpath:application-mysql.yml", factory = YamlPropertySourceFactory.class)
public class DBConfigByYml {

@Value("${spring.datasource.driver-class-name}")
private String driverClassName;

@Value("${spring.datasource.url}")
private String url;

@Value("${spring.datasource.username}")
private String username;

@Value("${spring.datasource.password}")
private String password;

@Bean
public DataSource dataSource(){
return DataSourceBuilder.create()
.driverClassName(driverClassName)
.url(url)
.username(username)
.password(password)
.build();
}
}
Share