工具类的静态方法中要使用别的对象类和使用@value注入成员变量,由于静态方法是属于类的,普通方法才属于对象,spring注入是在容器中实例化变量的,静态是先于对象加载的,所以直接在静态方法中调用注入的静态变量会报空指针异常。所以需要做一些处理
用到的注解@Component、@Autowired、@PostConstruct、@Value
例如:
@Component
public class TestUtil {
private static TestUtil testUtil ;
//使用@Autowired和@PostConstruct注入对象
@Autowired
private TargetClass targetClass;
@PostConstruct
public void init() {
testUtil = this;
testUtil .targetClass= this.targetClass;
}
//使用@Value注入变量
//不能直接在静态变量上使用@Value注入,Spring的@Value依赖注入是依赖set方法,set方法是普通的对象方法,static变量是类的属性,static没有set方法。
//但是Spring支持set方法注入,可以利用非静态的setter方法注入静态常量。注意set方法不能有static
private static String targetString;
@Value("${target_value}")
private void setTargetString(String targetString){
TestUtil.targetString=targetString;
}
//静态方法
public static void testMathod() {
String xxx = testUtil.targetClass.getTargetTest();
System.print.out(xxx);
System.print.out(targetString);
}
}