场景:
在某个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()方法!
动态获取Spring Bean实例的实现
本文介绍如何在Java中通过实现ApplicationContextAware接口动态获取Spring框架管理的其他bean实例,详细解释了接口的作用及使用场景。

被折叠的 条评论
为什么被折叠?



