码迷,mamicode.com
首页 > 移动开发 > 详细

通过实现ApplicationContextAware接口动态获取bean

时间:2016-09-27 22:51:48      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

转载自:http://penghuaiyi.iteye.com/blog/2042296

场景:

在代码中需要动态获取spring管理的bean

代码:

SpringContextUtils.java

package com.winner.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring的工具类,用来获得配置文件中的bean
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     *  当继承了ApplicationContextAware类之后,那么程序在调用 getBean(String)的时候会自动调用该方法,
     * 不用自己操作
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /***
     * 根据一个bean的id获取配置文件中相应的bean
     */
    public static Object getBean(String beanId) throws BeansException {
        if (applicationContext.containsBean(beanId)) {
            applicationContext.getBean(beanId);
        }
        return null;
    }

    /***
     * 根据一个bean的类型获取配置文件中相应的bean
     */
    public static <T> T getBeanByClass(Class<T> requiredType) throws BeansException {
        return applicationContext.getBean(requiredType);
    }

    /**
     * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
     */
    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static ApplicationContext getApplicationContext() {
        return SpringContextUtils.applicationContext;
    }
}

这几个注解所在的包是

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.2.5.RELEASE</version>
</dependency>

SpringContextUtils必须放在Spring容器中

要么在xml配置文件中声明,要么加上注解

 

 

通过实现ApplicationContextAware接口动态获取bean

标签:

原文地址:http://www.cnblogs.com/winner-0715/p/5914388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!