2011-08-20 164 views
23

从属性文件中为最终属性注入Spring的简单问题。最终属性中的Spring属性注入@Value - Java

我有我要存储在一个文件路径的属性文件,通常当我使用属性文件,我设置类使用这样的属性:

private @Value("#{someProps['prop.field']}") String someAttrib ; 

然后我spring.xml我会像:

<util:properties id="someProps" 
    location="classpath:/META-INF/properties/somePropFile.properties" /> 

这个效果很好,很简单,使代码很好,很整洁。但我不确定在试图将属性值注入最终类属性时使用的最佳模式是什么?

显然是这样的:

private static final @Value("#{fileProps['dict.english']}") String DICT_PATH; 

将无法​​正常工作。有另一种方法吗?

干杯!

+2

没有,这两种方法是不兼容的。 – skaffman

回答

24

您可以将值注入最终字段的唯一方法是通过Constructor Injection。其他所有的东西都会在Spring的方面非常糟糕。

+1

有没有这样的例子? – wheeler

0

如果你正在寻找一个例子:

public class Test { 


    private final String value; 
    public Test(@Value("${some.value}") String value){ 
     this.value=value; 
     System.out.println(authURL); 
    } 
    }