问题缘由:

有些工具类中的静态方法需要依赖别的对象实例(该实例已在spring容器中)

因为静态方法里面的变量必然要使用静态成员变量,此时如果直接使用@Autowired:

@Component
public class TestClass {

    @Autowired
    private static AutowiredTypeComponent component;

    // 调用静态组件的方法
    public static void testMethod() {
        component.callTestMethod();
    }

}

编译正常,但运行时报java.lang.NullPointerException: null异常,显然在调用testMethod()方法时,component变量还没被初始化,报NPE。

原因

在Spring里,我们是不能@Autowired一个静态变量。为什么?其实很简单,因为当类加载器加载静态变量时,Spring上下文尚未加载。所以类加载器不会在bean中正确注入静态类,并且会失败。

解决方案

给静态组件加setter方法,并在这个方法上加上@Autowired。Spring能扫描到AutowiredTypeComponent的bean,然后通过setter方法注入。示例如下:

@Component
public class TestClass {

    private static AutowiredTypeComponent component;

    @Autowired
    public void setComponent(AutowiredTypeComponent component){
        TestClass.component = component;
    }

    // 调用静态组件的方法
    public static void testMethod() {
        component.callTestMethod();
    }

}

参考链接:https://blog.csdn.net/RogueFist/article/details/79575665

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐