2014-02-16 17 views
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:空被打印出来,我可能会丢失这里?

+1

如果使用“new”运算符创建一个新的常量实例,它将不会由Spring管理,因此您不能使用依赖注入。你需要从Spring的ApplicationContext中加载它。 –

回答

0

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

所以从春

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

得到它或将其注入Sample豆。