首页 > 解决方案 > @ConfigurationProperties 不使用 PropertySourcesPlaceholderConfigurer

问题描述

PropertySourcesPlaceholderConfigurer适用于我@Value的 s 但不适用于以下广告数据源配置

@Bean
@ConfigurationProperties(prefix = "datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

我自定义PropertySourcesPlaceholderConfigurer解码配置文件中的密码,但在这个确切的地方没有触发解码功能,而它在其他地方工作。您能否提一些建议?

标签: javaspring-boot

解决方案


默认情况下,Spring 将使用简单/非包装ConfigurationPropertySource而不是更复杂的PropertySourcesPlaceholderConfigurer,它包含多个PropertySources。

可以在其内部找到一个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使用DataSourceProperties Bean填充,这是一个带@ConfigurationProperties注释的类

@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {

问题是,@ConfigurationProperties将 1:1 映射到属性文件,这是非常固执的。
@Value是另一种野兽。


我在这个答案中解决了一个完全自定义的实现。
你可能会觉得它很有价值。


推荐阅读