这个问题类似于这个问题:Spring: How to inject a value to static field?
但有一点曲折。
我需要在静态方法@BeforeClass
和@AfterClass
中使用注入的值。
我尝试创建@Component
并将application.properties
中的值提供给@PostConstruct
上的静态字段
A ...我得到一个空指针异常。
因此,该问题可以改写为
“我如何在@AfterClass / @BeforeClass方法中使用应用程序属性中的值?”
@Component
:
package com.vulog.pdfgenerator.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class GlobalValue {
@Value("${spring.thymeleaf.prefix}")
protected String prefix;
@Value("${template.tmpfolder}")
private String tmpfolder;
public static String tmpFolderStatic;
@Value("${template.classpath}")
private String classpath;
public static String classpathStatic;
/**
* Hack! we want to use the static methods BeforeClass/AfterClass
* so the app property values should be kept static as well.
*/
@PostConstruct
public void init(){
classpathStatic = classpath;
tmpFolderStatic = tmpfolder;
}
}
我将其自动连接到测试类,并尝试获取GlobalValue.classpathStatic但它抛出了。
@Autowired
GlobalValue globalValue;