Springboot中使用多线程,无法注入Service以及Jpa接口服务
在项目中遇到了一个问题,如题,如图。在运行的时候,使用@Autowired注入的服务均为null,也就是无法注入。
查找资料之后总结,个人觉得有两方面原因,也可以说两方面的解决手段
- new出来的线程,不在springboot的容器中,没办法自动注入(具体原理还不是特别懂,需要深入研究,也希望有大佬解答一下),需要手动注入
- 修改线程的编写方式,以Springboot的方式来新建一个线程。
先来讲第一种
参考:https://blog.****.net/u011493599/article/details/78522315
需要新建一个类实现ApplicationContextAware接口,接口中重写setApplicationContext方法。然后在线程的构造方法中手动注入被@service标记的类。
实现ApplicationContextAware接口的类(类名随意):
@Component
public class SpringBeanUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringBeanUtil.applicationContext = applicationContext;
}
public static Object getBeanByName(String beanName) {
if (applicationContext == null){
return null;
}
return applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> type) {
return applicationContext.getBean(type);
}
}
然后就是在编写线程代码的时候,在构造方法中获取要获取的服务
@Service
@Component
public class DetectionThread extends Thread {
private PictureRespository pictureRespository;
private DetectionService detectionService;
private RetangleRespository retangleRespository;
public DetectionThread(){
this.pictureRespository = SpringBeanUtil.getBean(PictureRespository.class);
System.out.println(11);
}
public void run(){
}
}
关于第二种,如何更好的将线程加入到Springboot容器中,也就是利用框架的方式开一个线程,待更新