在写一个工具类的时候遇到问题:使用@Autowired无法自动注入bean。报空指针异常,获取到的对象值为null。
经过一番摸索实践,探究到根本原因:工具类使用@Autowired无法注入bean的原因大多是因为使用了静态方法,相应的,使用@Autowired注入的对象也应该被static修饰,这样spring就无法正常注入bean,找到了原因,我也总结了三种解决方法。
第一种是我认为最简单的方法,如下,因为使用了static修饰的原因导致报错,直接去掉star的static修饰和方法的static修饰,然后把工具类交给spring管理即可。
package ts.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TestUtil {
@Autowired
// private static Star star;
private Star star;
// public static void testStar() {
// star.do1();
// }
public void testStar() {
star.do1();
}
}
spring配置文件需扫描工具类包
<context:component-scan base-package="ts.util" />
相应的使用时需注入TestUtil。
@Autowired
TestUtil testUtil;
public void test02() {
testUtil.testStar();
}
第二种方法,就是在构造函数上使用@Autowired。
package ts.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TestUtil {
private static Star star;
@Autowired
public TestUtil(Star star) {
TestUtil.star = star;
}
public static void testStar() {
star.do1();
}
}
@Autowired 注解,可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。
使用时直接调用即可。
public void test02() {
TestUtil.testStar();
}
第三种方法,使用@PostConstruct注解
package ts.util;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TestUtil {
private static Star star;
@Autowired
private Star sta2;
@PostConstruct
public void init() {
star = sta2;
}
public static void testStar() {
star.do1();
}
}
@PostConstruct:被@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
使用时直接调用即可。
public void test02() {
TestUtil.testStar();
}
总结:总的来说,静态变量、静态方法不是对象的属性,而是一个类的属性,所以静态方法是属于类(class)的,普通方法才是属于实体对象(也就是New出来的对象)的,spring注入是在容器中实例化对象的,并且静态是优先于对象存在的,所以直接在静态方法中调用注入的静态变量其实是为null的。归根结底,sping中如果要对静态变量进行注入只能是变相、间接的来完成。