Spring:@PropertySource的程序化等价物是什么

Ami*_*iri 5 java spring

请考虑以下设置:

@Configuration
@PropertySource("classpath:common.properties")
public class CommonConfig {

}
Run Code Online (Sandbox Code Playgroud)

现在让我们假设我想要在这个配置中加载的属性源和一些属性源背后有一些非平凡的逻辑,我想为此使用属性API:

@Configuration
public class CommonConfig {

    @Autowired
    private ConfigurableEnvironment env;

    public void loadCommonConfig() {
        // Determine what properties to load and how...
        env.getPropertySources().addLast(...);
    }

}
Run Code Online (Sandbox Code Playgroud)

我不明白我应该如何通知Spring我有兴趣在loadCommonConfig生命周期中被调用的地方@PropertySource.简单地返回属性作为一个@Bean似乎没有工作.

Gau*_*UES 6

您必须声明一个PropertySourcesPlaceholderConfigurer静态 bean 才能使@PropertySource注释工作(或使用 SpringBoot 为您声明它)。

您可以在声明此 bean 时使用方法手动加载属性文件setLocations(...)

这是一个例子:

@Configuration
public class CommonConfig {
...
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
            PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
            ppc.setLocations(new FileSystemResource("/etc/webapp_properties/security-token.properties"),
                    new ClassPathResource("config/WebApp.properties"),
                    new ClassPathResource("config/" + System.getenv("CURRENTENV") + "/WebApp.properties"));
            return ppc;
        }
...
}
Run Code Online (Sandbox Code Playgroud)

  • 如果解释了为什么使用 `static`,我会给这个投票。 (2认同)
  • @fwonce 可能有点晚了,但这就是使用 static 的原因 - 是在 Spring 容器生命周期的早期实例化 `propertyPlaceholderConfigurer` bean,并让它干扰要替换的 `@Value` 注释的处理它们与实际的财产价值。 (2认同)
  • 从官方文档中查看有关使用“static”的内容 - “必须特别考虑返回 Spring BeanFactoryPostProcessor (BFPP) 类型的 @Bean 方法。由于 BFPP 对象必须在容器生命周期的早期实例化,因此它们可能会干扰 @Configuration 类中 @Autowired、@Value 和 @PostConstruct 等注释的处理。为了避免这些生命周期问题,请将 BFPP 返回 @Bean 方法标记为静态。` [spring 文档链接](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/注释/Bean.html) (2认同)