很多时候我们在一些不受spring管理的类中需要用到spring管理的Bean,那么这个时候可以使用如下工具类从spring容器中获取相关的Bean实例。
@Component
public class SpringApplicationContextUtils implements ApplicationContextAware {
private static final Logger log = LoggerFactory.getLogger(SpringApplicationContextUtils.class);
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
log.info("【Spring】注入spring容器开始,context:{}", context);
if(applicationContext == null) {
applicationContext = context;
}
log.info("【Spring】注入spring容器结束,SpringApplicationContextUtils.applicationContext:{}", applicationContext);
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
public static <T> T getBean(String beanName, Class<T> clazz) {
return applicationContext.getBean(beanName, clazz);
}
}