通过实现ApplicationContextAware接口获取bean

来源:互联网 发布:淘宝嘉年华和双11 编辑:程序博客网 时间:2024/06/14 08:38

场景:

在某个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()方法!

 

原创粉丝点击