如何使用@Value将属性值注入静态字段

Chi*_*tel 4 java spring

我有一个属性文件config.properties,它使用spring属性占位符配置.这是我在spring配置文件中配置的方式:

<context:property-placeholder location="classpath:properties/config.properties"/>
Run Code Online (Sandbox Code Playgroud)

现在我需要使用@Value注释将其值设置为静态字段.

@Value("${outputfilepath}")
private static String outputPath;
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

nes*_*ant 13

唯一的方法是使用setter来获取此值

@Value("${value}")
public void setOutputPath(String outputPath) {
    AClass.outputPath = outputPath;
} 
Run Code Online (Sandbox Code Playgroud)

但是你应该避免这样做.弹簧不适用于静态注射.因此,您应该使用另一种方法在应用程序的开头设置此字段,例如构造函数.无论如何@Value注释使用spring PropertyPlaceholder,它在静态字段初始化后仍然被解析.因此,这种结构不会有任何好处