场景:
在某个bean中需要动态获取其它bean
实例代码:
packageorg.company.xxx;
importorg.springframework.beans.BeansException;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.ApplicationContextAware;
public class Demo implements ApplicationContextAware {
// Spring应用上下文环境
private ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
*/
publicvoid setApplicationContext(ApplicationContext applicationContext)throws BeansException {
this.applicationContext= applicationContext;
}
public Object getBean(String beanId)throws BeansException {
return applicationContext.getBean(beanId);
}
}
注:实现了ApplicationContextAware接口,在Bean的实例化时会自动调用setApplicationContext()方法!