【问题标题】:Spring PropertySourcesPlaceholderConfigurer in library库中的 Spring PropertySourcesPlaceholderConfigurer
【发布时间】:2018-02-02 15:18:15
【问题描述】:

背景:我正在编写一个将被编译成 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-app也使用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 检索属性值

【问题讨论】:

标签: spring spring-mvc


【解决方案1】:

你可以做一个实验,在同一个类路径中的两个不同配置中创建同一个 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 被另一个覆盖。 但是,如果您会明确地帮助 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。 It is explained here 也可以配置为DefaultListableBeanFactory。检查这个答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-30
    • 2013-03-08
    • 2015-01-13
    • 2020-01-21
    • 2016-07-19
    • 2014-12-03
    • 2021-02-12
    • 2015-08-01
    相关资源
    最近更新 更多