0
我constants.java是這樣的:@Value沒有工作,即使關鍵是解決[春季4]
@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());
}
}
我可以:
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;
}
}
我使用彈簧啓動這樣的應用程序加載見以下打印在日誌:
20:40:45865 DEBUG PropertySourcesPropertyResolver:90 - 實測值密鑰 'allowxmlvalue' 在[URL [/home/ubuntu/config/properties/app.properties]類型[字符串] 和值「打印XML值」
但還是打印XML:空被打印出來,我可能會丟失這裏?
如果使用「new」運算符創建一個新的常量實例,它將不會由Spring管理,因此您不能使用依賴注入。你需要從Spring的ApplicationContext中加載它。 –