关于springboot使用@Autowired注解向非controller类中注入bean为null的问题
2019-05-09 15:59
2611 查看
这种问题一般分为2种情况
第一种情况,如果你要在java A类中 使用@Autowired注入java B类,如果注入不了的话,通过添加以下三个关键的地方,可以解决该问题:
关于@PostConstruct:被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行
[code] @Component public class A{ @Autowired public B b; public static A a; @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作 public void init() { a= this; a.b= this.b; }
有三个地方需要注意一下(敲黑板!):
1.@Component
2.public static A a; 注意这个为 public 不然没有权限
3.@PostConstruct public void init() {}
第二种情况:你要被注入的类继承了thread类,这样的话你通过上面的方法来做的,仍然注入不进去,原因是因为spring的非线程安全问题,不让你注入,注入的结果是null
解决办法写一个构造函数或者set和get方法把你要注入的service传进来就好
参考文档
https://blog.csdn.net/qiangrenpu8881/article/details/82146323
相关文章推荐
- 解决 SpringMvc 非controller类使用@Autowired注解 service注入为null的问题
- 解决非controller使用@Autowired注解注入为null问题
- @webservice 注解的类中使用@Autowired 进行bean注入,注入的bean调用时为空的问题
- 【SpringBoot】拦截器使用@Autowired注入接口为null解决方法
- 【SpringBoot】拦截器使用@Autowired注入接口为null解决方法
- SpringBoot项目使用多线程处理定时任务时无法通过@Autowired注入bean
- 【SpringBoot】拦截器使用@Autowired注入接口为null解决方法
- [Spring Boot实战系列] - No.4 Spring boot 中如何在Utils类中使用@Autowired注入bean
- 解决非controller使用@Autowired注解注入为null问题
- 关于Struts在Spring中使用autowired 自动注入的问题
- 关于Struts在Spring中使用autowired 自动注入的问题
- SSM SpringMVC 非Controller类使用@Autowired注解Service为null的解决办法
- 解决非controller使用,@Autowired或者@Resource注解注入Mapper接口为null的问题
- 关于spring boot自动注入出现Consider defining a bean of type 'xxx' in your configuration问题解决方案
- Spring 注解Autowired自动注入bean异常解决
- spring@Autowired注入为null的问题,2017年9月14日21点41分记录
- Spring Boot @Autowired 没法自动注入的问题
- Spring Boot @Autowired 没法自动注入的问题
- Spring系列【04】应用@Autowired注解实现Bean的注入
- Spring 注解实现Bean依赖注入之@Autowired