我想通过.proprerties文件配置我的bean字符串字段。但是它不会替换值键,意味着它回显“$ {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!

最佳答案

好像您的配置中缺少PropertySourcesPlaceholderConfigurer。

参见this post

07-27 13:44