请考虑以下设置:
@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似乎没有工作.
您必须声明一个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)
| 归档时间: |
|
| 查看次数: |
2539 次 |
| 最近记录: |