实现一个线程继承了Thread或实现Runnable接口,想在run方法中使用spring依赖注入(操作数据库),此时报错为空指针,就是说没有注入进来。

实验了几种方式,分别说一下优缺点。

1:写了工具类,实现ApplicationContextAware接口,做一个通过name获取实例的方式,代码如下:

 1 public class SpringUtil implements ApplicationContextAware {
 2 
 3     private static ApplicationContext ctx = null;
 4 
 5     @Override
 6     public void setApplicationContext(ApplicationContext applicationContext)
 7             throws BeansException {
 8 
 9         if (SpringUtil.ctx == null) {
10             SpringUtil.ctx = applicationContext;
11         }
12     }
13 
14     public static ApplicationContext getCtx() {
15         return ctx;
16     }
17     
18     public static Object getBean(String name) {
19         return getCtx().getBean(name);
20     }
21     
22 
23 }
View Code

相关文章:

  • 2021-12-03
  • 2021-10-10
  • 2021-09-16
猜你喜欢
  • 2021-12-30
  • 2021-05-27
  • 2022-03-06
  • 2021-06-12
  • 2021-09-29
  • 2021-07-18
  • 2021-08-07
相关资源
相似解决方案