@ConfigurationProperties不使用PropertySourcesPlaceholderConfigurer

问题描述 投票:1回答:1

PropertySourcesPlaceholderConfigurer适用于我的@Values,但未用于以下广告数据源配置

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

我定制了PropertySourcesPlaceholderConfigurer来解码配置文件中的密码,但是在这个确切的地方没有触发解码功能,而它可以在其他地方使用。您能否提一些建议?

java spring-boot
1个回答
1
投票

默认情况下,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 Bean填充DataSourceProperties,这是一个@ConfigurationProperties注释类

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

问题是,@ConfigurationProperties将1:1映射到属性文件,它非常自以为是。 @Value是一个不同的野兽。


我在this回答中解决了一个完全自定义的实现。 你可能会发现它很有价值。

© www.soinside.com 2019 - 2024. All rights reserved.