【问题标题】:Can't pull values from .properties file using annotations无法使用注释从 .properties 文件中提取值
【发布时间】:2014-02-11 02:47:28
【问题描述】:

我想通过 .proprerties 文件配置我的 bean 字符串字段。但它不会替换 value 键,这意味着它会回显“${value}”字符串。我的代码如下:

主类:

public class Main {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
        ValuesContainer valuesContainer = (ValuesContainer) applicationContext.getBean("container");
        System.out.println(valuesContainer.getValue()); //echoes "${value}" instead of Ho-ho-ho!
    }
}

应用上下文:

.....
<context:annotation-config />
<context:component-scan base-package="bean"/>

豆子:

package bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("container")
@Scope("singleton")
@PropertySource(value = "classpath:app.properties")
public class ValuesContainer {

    @Value("${value}")
    private String value;

    public String getValue() {
        return value;
    }
}

app.properties:

value = Ho-ho-ho!

【问题讨论】:

    标签: java spring


    【解决方案1】:

    @PropertySource 应与@Configuration 一起使用。

    您需要创建一个单独的@Configuration 类,将您的注解@PropertySource 添加到您的应用程序上下文中(或者让&lt;context:component-scan&gt; 添加它)。

    或者,您可以通过编程方式配置应用程序上下文的属性源,using Environment

    【讨论】:

      【解决方案2】:

      您的配置中似乎缺少 PropertySourcesPlaceholderConfigurer。

      this post

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-02
        • 2021-12-11
        • 2013-11-19
        • 2017-07-09
        • 2015-03-13
        • 2021-11-28
        • 2014-10-12
        • 1970-01-01
        相关资源
        最近更新 更多