Spring boot项目中线程中无法注入bean的可替代方法
作者:互联网
在spring编程过程中,多线程中是我们经常使用的,但是在线程中,我们是无法通过@Autowired注解来注入我们想要的bean的,所以需要向另外的方法来实现,下面是两种实现方式
1、通过线程的构造函数将需要的bean在构造线程的时候通过调用者注入bean,通过构造函数注入相应bean来实现
2、通过SpringIoc容器beanfactory或者applicationcontext来获取对应的bean
通过继承ApplicationContextAware来获取applicationcontext
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static Object getBean(String beanName){
return applicationContext.getBean(beanName);
}
public static Object getBean(Class o){
return applicationContext.getBean(o);
}
}
通过继承BeanFactoryAware 获取beanfactory容器
@Component
public class BeanFactoryHolder implements BeanFactoryAware {
private static BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
标签:applicationContext,beanFactory,Spring,boot,getBean,程中,bean,static,public 来源: https://www.cnblogs.com/hik-wolf/p/12634143.html