库中的Spring属性资源占位符配置器
背景:我正在编写一个库,它将被编译成JAR文件。该库将在许多web应用程序中用作依赖项。图书馆和网络应用程序都在使用Spring。web应用程序有责任在库类上运行ComponentScan以获取任何SpringBean/配置 询问:在库中,我想使用PropertySourcesPlaceholderConfigurer从属性文件加载属性。大概是这样的:库中的Spring属性资源占位符配置器,spring,spring-mvc,Spring,Spring Mvc,背景:我正在编写一个库,它将被编译成JAR文件。该库将在许多web应用程序中用作依赖项。图书馆和网络应用程序都在使用Spring。web应用程序有责任在库类上运行ComponentScan以获取任何SpringBean/配置 询问:在库中,我想使用PropertySourcesPlaceholderConfigurer从属性文件加载属性。大概是这样的: package com.blah; import org.springframework.context.annotation.Bean; i
package com.blah;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySource("classpath:properties/blah.${environment}.properties")
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
这很好用
问题:如果作为依赖项加载此库的web应用程序也使用PropertySourcesPlaceholderConfigurer加载属性,那么两者之间是否存在冲突?一个会覆盖另一个(即使属性不同)?或者他们能和平和谐地生活在一起吗
使用弹簧3.2.4
更新 根据Bogdan Oros在下面的回答,这看起来是可以的,即它们不会冲突,两组属性都将被加载。我创建了两个配置文件:
@Configuration
@PropertySource("classpath:properties/blah.stage1.properties")
public class BlahClientConfig1 {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
及
当我运行测试时,我可以成功地从blah.stage1.properties和blah.stage2.properties中检索属性值您可以在同一类路径中的两个不同配置中创建同一个bean,这将起作用
@Configuration
class AConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer resolver() {
return new PropertySourcesPlaceholderConfigurer();
}
}
@Configuration
class B {|
@Bean
public static PropertySourcesPlaceholderConfigurer resolver() {
return new PropertySourcesPlaceholderConfigurer();
}
}
它将正常工作,因为spring解决了这种情况。
您将发现一个bean被另一个bean覆盖。
但是,如果您愿意帮助spring和安装程序显式地命名
@Configuration
class A {
@Bean(name="resolver")
public static PropertySourcesPlaceholderConfigurer resolver() {
return new PropertySourcesPlaceholderConfigurer();
}
}
@Configuration
class B {
@Bean(name="resolver")
public static PropertySourcesPlaceholderConfigurer resolver() {
return new PropertySourcesPlaceholderConfigurer();
}
}
这种情况将导致注入失败,因为它无法决定注入哪个bean。
还可以使用DefaultListableBeanFactory
配置它。检查此答案。您检查了此答案吗?
@Configuration
class A {
@Bean(name="resolver")
public static PropertySourcesPlaceholderConfigurer resolver() {
return new PropertySourcesPlaceholderConfigurer();
}
}
@Configuration
class B {
@Bean(name="resolver")
public static PropertySourcesPlaceholderConfigurer resolver() {
return new PropertySourcesPlaceholderConfigurer();
}
}