【问题标题】:Injecting property files overriding the one defined in the application注入覆盖应用程序中定义的属性文件
【发布时间】:2015-05-21 14:20:14
【问题描述】:

在将属性值注入到 Web 应用程序外部定义的 bean 时,我需要一些帮助。

web应用在src/main/resource下有一个属性文件。spring应用上下文xml有属性占位符定义为

<context:property-placeholder
        location="classpath:test.properties,file:/etc/test1.properties"
        ignore-resource-not-found="true"
    />

其中 test1.properties 是位于应用程序外部的另一个文件。bean 注入了应用程序 (test.properties) 中定义的属性,但我想注入 test1.properties 中定义的属性(理想的想法是覆盖应用程序的属性值并读取应用程序外部定义的值)。

谢谢。

【问题讨论】:

  • 它应该如何工作,如果不是我怀疑你的文件没有被读取。
  • 该bean带有Component注解,并且该包是组件扫描的一部分。因此spring容器加载bean并注入依赖但不读取应用程序外部的属性文件值。任何指针都会很有帮助。
  • 然后找不到文件。我很确定当您将 ignore-resource-not-found 设置为 false 时,您的应用程序会中断。

标签: java spring


【解决方案1】:

你好在applicationContext.xml中使用如下

<util:properties id="property" location="classpath:test.properties"/>

在 Java 中,

@Autowired
    protected Properties property;

【讨论】:

    【解决方案2】:

    我猜这就是你要找的东西

    <context:property-placeholder location="file:c:/kp/sec.properties" order="1" ignore-resource-not-found="true" ignore-unresolvable="true" />
    
    <context:property-placeholder location="classpath:kp-props.properties" order="2" />
    

    如果文件 sec.properties 存在,则从 sec.properties 中获取值,如果文件或属性不存在,则从资源目录中的 kp-props.properties 文件中获取属性(如果在任何地方应用程序中都找不到该属性会失败)

    假设您有属性my.prop,您可以按如下方式注入该属性。

    @Component
    public class KPProps {
    
        @Value("${my.prop}")
        private int props;
    
        public void print(){
            System.out.println(props);
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      • 1970-01-01
      • 2019-03-02
      • 2021-10-20
      相关资源
      最近更新 更多