springboot @Autowired bean注入失败解决方案
项目中常常会踩到一些莫名其妙的坑,而且怎么发生的为什么发生的怎么解决的,让一些萌新都很懵。有一些不仅是萌新看了一脸懵,就连老手看了也一脸懵,然后一步一步debug看debug走 hahahhaha~可见原理底层的重要性!
1.ServiceImpl实现类注入Mapper为null时,确定Mapper是否加类注解@Mapper并检查Service实现类是否添加类注解@Service。
2.Controller注入Service为null时,确定Service实现类是否添加类注解@Service。
如图:
3.执行类/工具类/定时任务 @Autowired注入Service抛空指针异常,使用@Component与@PostConstruct
@Component : 把普通pojo实例化到spring容器中
@PostConstruct :PostConstruct在构造函数之后执行,只会执行一次
如图:
原理:先执行的是静态方法,这个时候@Autowired注入的组件还没有完成所以是null,然后执行
@PostConstruct的init进行初始化,这个时候bean已经注入进来,给赋值一下就好了!
4.项目框架或其他莫名其妙的问题导致Controller层注入Service失败
对于这种情况,网上早有些解决方案,而我采用的也是写一个直接去类取bean的工具类:实现ApplicationContextAware接口,定义一个静态的ApplicationContext(Spring应用上下文环境)
下面直接发代码:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component("springContextUtils")
public class SpringContextUtils implements ApplicationContextAware {
/**
* Spring应用上下文环境
*/
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
*
* @param applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtils.applicationContext = applicationContext;
}
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取对象
*
* @param name
* @return Object
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
/**
* 根据class获取对应的bean对象
* @param clz
* @return
*/
public static Object getBean(Class<?> clz){
return applicationContext.getBean(clz);
}
}
调用:
取bean:
BrokenPointService brokenPointService = (BrokenPointService) SpringContextUtils.getBean(BrokenPointService.class);
方法内调用:
brokenPointService.xxxx(xxx);