Java Can';t使用注释从.properties文件中提取值

Java Can';t使用注释从.properties文件中提取值,java,spring,Java,Spring,我想通过.proprerties文件配置我的bean字符串字段。但它不替换value键,意味着它回显“${value}”字符串。我的代码如下: 主要类别: 应用程序上下文: app.properties: 您的配置中似乎缺少PropertySourcesPlaceholderConfigurer 请参阅。@PropertySource应与@配置一起使用 您需要创建一个单独的@Configuration类,将注释@PropertySource放在其上,并将其添加到应用程序上下文中(或者让来添加它)

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

主要类别:

应用程序上下文:

app.properties:


您的配置中似乎缺少PropertySourcesPlaceholderConfigurer


请参阅。

@PropertySource
应与
@配置一起使用

您需要创建一个单独的
@Configuration
类,将注释
@PropertySource
放在其上,并将其添加到应用程序上下文中(或者让
来添加它)

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

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;
    }
}
value = Ho-ho-ho!