【发布时间】: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