编写一个工具类实现ApplicationContextAware接口,重写setApplicationContext方法
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext context;
/**
* Set the ApplicationContext that this object runs in.
* Normally this call will be used to initialize the object.
* <p>Invoked after population of normal bean properties but before an init callback such
* as {@link InitializingBean#afterPropertiesSet()}
* or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
* and
* {@link MessageSourceAware}, if applicable.
*
* @param applicationContext the ApplicationContext object to be used by this object
* @throws ApplicationContextException in case of context initialization errors
* @throws BeansException if thrown by application context methods
* @see BeanInitializationException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
/**
* 获取bean
* @param beanName
* @return
*/
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
}
在需要引入的类中获取bean
public Bean getTemp() {
return (Bean) ApplicationContextUtils.getBean("temp");
}
这样就引入进来了,直接调用就可以