通过实现ApplicationContextAware接口获取bean
2012-06-26 16:50
405 查看
场景:
在代码中需要动态获取其它bean
实例代码:
Bean配置:
注:
1、实现了ApplicationContextAware接口,在Bean的实例化时会自动调用setApplicationContext()方法!
2、通过调用静态方法getBean即可获取
在代码中需要动态获取其它bean
实例代码:
package org.company.xxx; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * 获取spring容器,以访问容器中定义的其他bean */ public class SpringContextUtil implements ApplicationContextAware { // Spring应用上下文环境 private static ApplicationContext applicationContext; /** * 实现ApplicationContextAware接口的回调方法,设置上下文环境 */ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 获取对象 这里重写了bean方法,起主要作用 * * @param name * @return Object 一个以所给名字注册的bean的实例 * @throws BeansException */ public static Object getBean(String beanId) throws BeansException { return applicationContext.getBean(beanId); } }
Bean配置:
<beanid="SpringContextUtil"class="org.company.xxx.SpringContextUtil"/>
注:
1、实现了ApplicationContextAware接口,在Bean的实例化时会自动调用setApplicationContext()方法!
2、通过调用静态方法getBean即可获取
相关文章推荐
- Spring中通过实现ApplicationContextAware接口获取bean
- 通过实现ApplicationContextAware接口动态获取bean
- 【ApplicationContext】通过实现ApplicationContextAware接口获取bean
- @SpringContext通过实现ApplicationContextAware接口动态获取bean
- 通过实现ApplicationContextAware接口获取bean
- 通过实现ApplicationContextAware接口获取bean
- 通过实现ApplicationContextAware接口获取bean
- 多线程中实现ApplicationContextAware接口获取需要的bean,applicationContext.getBea未返回也未报错
- Spring中通过实现FactoryBean接口获取bean实例
- Spring中ApplicationContextAware实现获取bean的工具类,在servlet中通过servletContext获取application
- 通过ApplicationContextAware接口获取Spring配置文件中的所有Bean
- Spring实现Aware接口自定义获取bean的两种方式
- 8. Struts2_通过 Aware 接口获取 WEB 资源
- Spring 获取 实现某接口的所有实例bean
- 通过ApplicationContextAware获取bean
- 用BeanFactoryAware接口,用BEAN的名称来获取BEAN对象
- 如何手动获取Spring容器中的bean(ApplicationContextAware 接口)
- 实现ApplicationContextAware接口时,获取ApplicationContext为null
- 通过ApplicationContextAware加载Spring上下文环境(获取bean)
- Spring中使用两种Aware接口自定义获取bean