我有一个属性文件config.properties,它是使用spring属性占位符配置的。这是我在spring配置文件中配置的方式:
<context:property-placeholder location="classpath:properties/config.properties"/>
现在我需要使用@Value注释将其值设置为 static 字段。
@Value("${outputfilepath}")
private static String outputPath;
我怎样才能做到这一点?
答案 0 :(得分:13)
唯一的方法是使用setter来获取此值
@Value("${value}")
public void setOutputPath(String outputPath) {
AClass.outputPath = outputPath;
}
但是你应该避免这样做。弹簧不适用于静态注射。因此,您应该使用另一种方法在应用程序的开头设置此字段,例如构造函数。 无论如何@Value注释使用spring PropertyPlaceholder,它在静态字段初始化后仍然被解析。因此,这种结构不会有任何好处
答案 1 :(得分:0)
更好的方法是使用静态 setter 来模拟最终方面,该方法只会在当前为 null 时设置该值。
private static String outputPath;
public static String getOutputPath(){
return outputPath;
}
private static setOutputPath( String op){
if (outputPath == null) {
outputPath = op;
}
}
@Value("${outputfilepath}")
private setOutputFilePath(String outputFilePath){
setOutputPath(outputFilePath);
}