每个@Configuration class 都需要 PropertySourcesPlaceholderConfigurer 吗?
Do I need PropertySourcesPlaceholderConfigurer for each @Configuration class?
我正在尝试使用 PropertySourcesPlaceholderConfigurer 在两个 @Configuration 类 中解析我的属性:InfrastructureContextConfiguration
和 WebMvcContextConfiguration
(两者都从同一个文件中获取属性),看起来两者都需要自己的PropertySourcesPlaceholderConfigurer
。
我可以同时使用一个 PropertySourcesPlaceholderConfigurer
和两个 类 吗?
在没有-xml 配置的Spring 应用程序中,必须在所有应用程序上下文中注册一个static PropertySourcesPlaceholderConfigurer bean。
要注册 PropertySourcesPlaceholderConfigurer,只需将相同类型的静态 bean 与您想要访问的 属性 源一起添加到配置中。要导入多个 属性 来源,请使用 @PropertySources 注释(在 Java 8 之前)或多个 @PropertySource 注释(Java 8)。
@Configuration
@PropertySource("classpath:application.properties")
@ComponentScan
class ApplicationConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
我在最近的博客 post 中提到了这一点:http://blog.codeleak.pl/2015/09/placeholders-support-in-value.html
您不需要在每个 @Configuration class 中注册 PropertySourcesPlaceholderConfigurer - 它在每个上下文中都是必需的 - 上下文可以使用多个 @Configuration class。您可以在 Spring MVC Quick Start Archetype 中找到示例:
https://github.com/kolorobot/spring-mvc-quickstart-archetype/tree/master/src/main/resources/archetype-resources/src/main/java/config
希望对您有所帮助。
我正在尝试使用 PropertySourcesPlaceholderConfigurer 在两个 @Configuration 类 中解析我的属性:InfrastructureContextConfiguration
和 WebMvcContextConfiguration
(两者都从同一个文件中获取属性),看起来两者都需要自己的PropertySourcesPlaceholderConfigurer
。
我可以同时使用一个 PropertySourcesPlaceholderConfigurer
和两个 类 吗?
在没有-xml 配置的Spring 应用程序中,必须在所有应用程序上下文中注册一个static PropertySourcesPlaceholderConfigurer bean。
要注册 PropertySourcesPlaceholderConfigurer,只需将相同类型的静态 bean 与您想要访问的 属性 源一起添加到配置中。要导入多个 属性 来源,请使用 @PropertySources 注释(在 Java 8 之前)或多个 @PropertySource 注释(Java 8)。
@Configuration
@PropertySource("classpath:application.properties")
@ComponentScan
class ApplicationConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
我在最近的博客 post 中提到了这一点:http://blog.codeleak.pl/2015/09/placeholders-support-in-value.html
您不需要在每个 @Configuration class 中注册 PropertySourcesPlaceholderConfigurer - 它在每个上下文中都是必需的 - 上下文可以使用多个 @Configuration class。您可以在 Spring MVC Quick Start Archetype 中找到示例: https://github.com/kolorobot/spring-mvc-quickstart-archetype/tree/master/src/main/resources/archetype-resources/src/main/java/config
希望对您有所帮助。