静态方法使用Spirng注入空指针问题

场景:

public class TestUtil {
    @Autowired
    private static MiniAppService staticMiniAppService;

    public static void test() {
        staticMiniAppService.getById(1);
    }
}

这样会报java.lang.NullPointerException: null异常
原因:
静态方法属于类,静态变量是类的属性,Spring注入需要实例化对象,所以不能使用静态方法

方案1
使用@Component和@PostConstruct实现静态类加载Spring自动注入

@Component
public class TestUtil {
    @Autowired
    private static MiniAppService staticMiniAppService;

    @Autowired
    private MiniAppService miniAppService;

    @PostConstruct
    public void init() {
        staticMiniAppService = miniAppService;
    }

    public static void test() {
        staticMiniAppService.getById(1);
    }
}

方案二
@Autowire加到构造方法上

@Component
public class TestUtil {
   
    private static MiniAppService staticMiniAppService;

   @Autowired
    public TestUtil (MiniAppService staticMiniAppService) {
        TestUtil .staticMiniAppService= staticMiniAppService;
    }

    public static void test() {
        staticMiniAppService.getById(1);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容