前言 我们经常会通过@Autowired注解将某个类注到另一个类中,但是会发现注不进去,报NULL。 可能的原因有一下几种: (1)该类没有托管给spring 管理 一般在类的上面添加@Component 就可以了 (2)你的这个类有被ne
我们经常会通过@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接口。
import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component; @Componentpublic 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); } public static T getBean(Class clazz) { return applicationContext.getBean(clazz); }}
案列:
SysDictService sysDictService = BeanUtils.getBean(SysDictService.class);
来源地址:https://blog.csdn.net/weixin_42826932/article/details/128559132
--结束END--
本文标题: @Autowired 注入为null 的原因与解决方式
本文链接: https://www.lsjlt.com/news/385849.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-03
2024-04-03
2024-04-01
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0