Spring中的PropertySourcesPlaceholderConfigurer

时间:2018-02-02 15:18:15

标签: spring spring-mvc

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

提问:在库中我想使用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中检索属性值

1 个答案:

答案 0 :(得分:2)

您可以在同一个类路径中以两种不同的配置创建相同的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覆盖了。 但是,如果您将帮助弹簧并明确设置名称

@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。 It is explained here也可以配置DefaultListableBeanFactory。检查这个答案。