场景:
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);
}
}