場(chǎng)景:
public class TestUtil {
@Autowired
private static MiniAppService staticMiniAppService;
public static void test() {
staticMiniAppService.getById(1);
}
}
這樣會(huì)報(bào)java.lang.NullPointerException: null異常
原因:
靜態(tài)方法屬于類回窘,靜態(tài)變量是類的屬性翘县,Spring注入需要實(shí)例化對(duì)象最域,所以不能使用靜態(tài)方法
方案1
使用@Component和@PostConstruct實(shí)現(xiàn)靜態(tài)類加載Spring自動(dòng)注入
@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加到構(gòu)造方法上
@Component
public class TestUtil {
private static MiniAppService staticMiniAppService;
@Autowired
public TestUtil (MiniAppService staticMiniAppService) {
TestUtil .staticMiniAppService= staticMiniAppService;
}
public static void test() {
staticMiniAppService.getById(1);
}
}