【问题标题】:@Value not working even if key is resolved [Spring 4]即使解决了密钥,@Value 也不起作用 [Spring 4]
【发布时间】:2014-02-16 15:27:59
【问题描述】:

我的constants.java是这样的:

package com.sample.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component(value="ConstantValues")
public class Constants {

    static {
        System.out.println("Class loaded: Constants");
    }

    @Value("${allowxmlvalue}") 
    private String logXMLString;

    public String getLogXMLString() {
        return logXMLString;
    }

    public void setLogXMLString(String logXMLString) {
        this.logXMLString = logXMLString;
    }

}

我正在使用这样的 spring boot 加载应用程序:

@Configuration
@PropertySources({
    @PropertySource("file:/home/ubuntu/config/properties/app.properties"),
    @PropertySource("file:/home/ubuntu/config/properties/util.properties")})
@ComponentScan(basePackages = { 
        "com.sample.utils"  
         })
@EnableAutoConfiguration
public class Sample {
    static Logger logger = Logger.getLogger(Sample.class);
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Sample.class, args);
        Constants cons = new Constants();
        logger.info("Print XML: "+cons.getLogXMLString());
    }
}

我可以在日志中看到以下打印:

20:40:45,865 调试 PropertySourcesPropertyResolver:90 - 找到密钥 [URL 中的“allowxmlvalue” [/home/ubuntu/config/properties/app.properties]] 类型为 [String] 和值'打印 xml 值'

但仍然打印 XML: null 被打印出来,我可能在这里遗漏了什么?

【问题讨论】:

  • 如果你使用“new”操作符创建一个新的Constant实例,它不会被Spring管理,所以你不能使用依赖注入。您需要从 Spring 的 ApplicationContext 加载它。

标签: spring configuration annotations


【解决方案1】:

您正在自己创建 Constants 实例,而不是获取 Spring 托管 bean。显然 Spring 不会处理它的字段。

所以从 Spring 获取它

ApplicationContext ctx = SpringApplication.run(Sample.class, args);
Constants cons = ctx.getBean(Constants.class);

或将其注入Sample bean。

【讨论】:

    猜你喜欢
    • 2018-11-17
    • 2020-04-17
    • 2011-10-30
    • 2021-11-29
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多