Spring boot project alternative methods can not be injected into the bean thread

In the spring programming, multithreading is that we often use, but in the thread, we are unable to inject the bean we want, so it is necessary to implement additional methods to @Autowired notes, here are two implementations the way

1, by the constructor bean thread will need to inject bean by the caller at the time of construction of the thread, into the corresponding bean by the constructor to achieve

2, to obtain the corresponding bean container beanfactory or by SpringIoc applicationcontext

Applicationcontext to get through inheritance ApplicationContextAware

@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;
}
}
 

Guess you like

Origin www.cnblogs.com/hik-wolf/p/12634143.html