在Spring里,我们不能@Autowired一个静态变量,使之成为一个spring bean。但静态方法里面的变量必然要使用静态成员变量。例如下面这样:
public class TestUtils {
@Autowired
private static DocService docService;
public static void CallUtil(){
docService.callMethod();
}
}
原因
在Spring中,是无法直接使用@Autowired注解到静态变量上,产生一个静态对象的。因为当Java的类加载器启动时,会先加载静态变量,而此时Spring上下文尚未加载,所以类加载器无法在bean中准确注入静态类,导致空指针异常。
解决方法
方法一
给静态组件加setter方法,并在这个方法上加上@Autowired
@Component
public class TestUtils {
private static DocService docService;
@Autowired
public void setDocService(DocService docService){
TestUtils.docService=docService;
}
public static void CallUtil(){
docService.callMethod();
}
}
方法二
将@Autowired 注解到类的构造函数上
@Component
public class TestUtils {
private static DocService docService;
@Autowired
public TestUtils(DocService docService){
TestUtils.docService=docService;
}
public static void CallUtil(){
docService.callMethod();
}
}
方法三
定义一个静态组件,定义一个非静态组件并加上@Autowired注解,再定义一个初始化组件的方法并加上@PostConstruct注解
@Component
public class TestUtils {
private static DocService docService;
@Autowired
private DocService autoDocService;
@PostConstruct
private void beforeInit() {
docService = autoDocService;
}
public static void CallUtil() {
docService.callMethod();
}
}