Spring PropertySourcesPlaceholderConfigurer in library



背景:我正在编写一个将编译成JAR文件的库。该库将用作许多 Web 应用程序中的依赖项。库和网络应用程序都在使用 Spring。Web应用程序有责任在库类上运行ComponentScan来获取任何Spring Bean/配置。

:在库中,我想使用 PropertySourcesPlaceholderConfigurer 从属性文件加载属性。像这样:

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 来加载属性,则两者之间是否存在冲突?一个会覆盖另一个吗(即使属性不同)?还是他们可以和平和谐地并肩生活?

使用 Spring 3.2.4


更新根据波格丹·奥罗斯(Bogdan Oros)下面的回答,看起来这没问题,即它们不会冲突,并且将加载两组属性。我创建了两个配置文件:

@Configuration
@PropertySource("classpath:properties/blah.stage1.properties")
public class BlahClientConfig1 {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}

@Configuration
@PropertySource("classpath:properties/blah.stage2.properties")
public class BlahClientConfig2 {
@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();
}
}

它将正常工作,因为春天解决了这种情况。 你会发现一个 bean 被另一个 bean 覆盖了。 但是,如果您将帮助弹簧并明确设置名称

@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。检查此答案。

最新更新