PropertySourcesPlaceholderConfigurer
适用于我的@Value
s,但未用于以下广告数据源配置
@Bean
@ConfigurationProperties(prefix = "datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
我定制了PropertySourcesPlaceholderConfigurer
来解码配置文件中的密码,但是在这个确切的地方没有触发解码功能,而它可以在其他地方使用。您能否提一些建议?
默认情况下,Spring将使用简单/非包装的ConfigurationPropertySource
而不是更复杂的PropertySourcesPlaceholderConfigurer
,它拥有多个PropertySource
s。
可以在DataSourceBuilder
本身找到一个例子
private void bind(DataSource result) {
ConfigurationPropertySource source = new MapConfigurationPropertySource(this.properties);
ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
aliases.addAliases("url", "jdbc-url");
aliases.addAliases("username", "user");
Binder binder = new Binder(source.withAliases(aliases));
binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));
}
对于那个片段,通常使用this.properties
Bean填充DataSourceProperties
,这是一个@ConfigurationProperties
注释类
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
问题是,@ConfigurationProperties
将1:1映射到属性文件,它非常自以为是。
@Value
是一个不同的野兽。
我在this回答中解决了一个完全自定义的实现。 你可能会发现它很有价值。