在最近的项目中,我想发送写一个发送邮件的工具类,使用的是mybatisplus3,使用@Autowired注入service时,在调用的时候空指针,上网查了很多资料,最终得以解决。
参考文章:@Autowired 注入的bean是null_autowired注入为 null-CSDN博客
有时候我们在某个类用@Autowired 进行注入时,会发现注入参数为null,这时候会有疑惑。
可能存在的原因:
(1)该类没有托管给spring 管理,一般在类的上面添加@Component 就可以了。
(2)你的这个类有被new出来的实例的,new 过的对象不会交给Spring容器管理 所以里面的 service或者dao注入不进来。一般是指引用某些框架,你是继承某个接口,但是这些框架默认new过这个方法,比如MVC拦截的HandlerInterceptor类。
如果要new的这个类里有想用@Autowired 自动注入的内容,则最好不好去new这个类,否则自动注入无效,为null;
解决办法:要用这个类的时候,这个类也用@Autowired 自动注入
有时候你确实需要在这个new 的类去注入某些类,但是用@Autowired 又注入为null,这时候我们需要手动去弄Spring容器中的Bean实现ApplicationContextAware接口。
(1)比如我想在某个类实现RedisUtils 类的注入,但是用@autowired 会报null
(2)这时候我们就要手动实现这个功能,写个BeanUtils 类 实现ApplicationContextAware接口
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class BeanUtils implements ApplicationContextAware {
protected static ApplicationContext applicationContext ;
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
if (applicationContext == null) {
applicationContext = arg0;
}
}
public static Object getBean(String name) {
//name表示其他要注入的注解name名
return applicationContext.getBean(name);
}
/**
* 拿到ApplicationContext对象实例后就可以手动获取Bean的注入实例对象
*/
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
}
注意:必须使用@Component注解
/**
* 由于不能用@Autowired进行注入,则使用这种手动注入方式
*/
private RedisUtils redisUtils = BeanUtils.getBean(RedisUtils.class);
这样就要正常引用redisUtils ,这样手动出来的跟@Autowire 一样的。