分享

通过实现ApplicationContextAware接口获取bean

 KILLKISS 2012-07-24

场景:

在代码中需要动态获取其它bean

实例代码:

01package org.company.xxx;
02 
03import org.springframework.beans.BeansException;
04import org.springframework.context.ApplicationContext;
05import org.springframework.context.ApplicationContextAware;
06 
07/**
08 * 获取spring容器,以访问容器中定义的其他bean
09 */
10public class SpringContextUtil implements ApplicationContextAware {
11 
12    // Spring应用上下文环境
13    private static ApplicationContext applicationContext;
14 
15    /**
16     * 实现ApplicationContextAware接口的回调方法,设置上下文环境
17     */
18    public void setApplicationContext(ApplicationContext applicationContext)
19            throws BeansException {
20        SpringContextUtil.applicationContext = applicationContext;
21    }
22 
23    public static ApplicationContext getApplicationContext() {
24        return applicationContext;
25    }
26 
27    /**
28     * 获取对象 这里重写了bean方法,起主要作用
29     *
30     * @param name
31     * <a href="http://my.oschina.net/u/556800" class="referer" target="_blank">@return</a>  Object 一个以所给名字注册的bean的实例
32     * @throws BeansException
33     */
34    public static Object getBean(String beanId) throws BeansException {
35        return applicationContext.getBean(beanId);
36    }
37}

Bean配置:

1<beanid="SpringContextUtil"class="org.company.xxx.SpringContextUtil"/>

注:

1、实现了ApplicationContextAware接口,在Bean的实例化时会自动调用setApplicationContext()方法!

2、通过调用静态方法getBean即可获取

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多