您的位置:首页 > 移动开发

通过实现ApplicationContextAware接口获取bean

2011-07-23 15:16 429 查看
场景:
在某个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()方法!
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bean spring object string class