Spring學習筆記四: 從Spring容器中獲取Bean

衣舞晨風發表於2016-07-14

通過BeanFactory獲取bean例項

package org.jiankunking.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

/**
 * Created by jiankunking on 2016/12/22.
 */
public class SpringBeanUtils implements BeanFactoryAware {

    private static BeanFactory beanFactory;

    /**
     * 注入BeanFactory例項
     */
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        SpringBeanUtils.beanFactory = beanFactory;
    }

    /**
     * 根據bean的名稱獲取相應型別的物件
     *
     * @param beanName bean的名稱
     * @return Object型別的物件
     */
    public static Object getBeanByName(String beanName) {
        return beanFactory.getBean(beanName);
    }

    /**
     * 根據bean的型別獲取相應型別的物件
     *
     * @param clazz bean的型別,沒有使用泛型
     * @return Object型別的物件
     */
    public static Object getBeanByClass(Class clazz) {
        WebApplicationContext wac = ContextLoader
                .getCurrentWebApplicationContext();
        Object bean = wac.getBean(clazz);
        return bean;
    }

    /**
     * 根據bean的名稱獲取相應型別的物件
     *
     * @param clazz bean的型別,使用泛型
     * @return T型別的物件
     */
    public static <T> T getGenericsBeanByClass(Class<T> clazz) {
        WebApplicationContext wac = ContextLoader
                .getCurrentWebApplicationContext();
        T bean = wac.getBean(clazz);
        return bean;
    }

}

在spring.xml中新增以下部分,已獲取工具類bean例項:

<bean id="springBeanUtils" class="org.jiankunking.utils.SpringBeanUtils"/>

通過ApplicationContext獲取bean例項

package org.jiankunking.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.DefaultResourceLoader;

import java.io.IOException;

/**
 * Spring的工具類,用來獲得Spring中的bean 
 */
public class SpringBeanUtils implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext;

    /**
     * 實現ApplicationContextAware介面的context注入函式, 將其存入靜態變數.
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringBeanUtils.applicationContext = applicationContext; // NOSONAR
    }

    /**
     * 取得儲存在靜態變數中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    /**
     * 從靜態變數ApplicationContext中取得Bean, 自動轉型為所賦值物件的型別.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 從靜態變數ApplicationContext中取得Bean, 自動轉型為所賦值物件的型別.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return (T) applicationContext.getBean(clazz);
    }

    /***
     * 類似於getBean(String name)只是在引數中提供了需要返回到的型別。
     *
     * @param name
     * @param requiredType
     * @return
     * @throws BeansException
     */
    public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return applicationContext.getBean(name, requiredType);
    }

    /**
     * 如果給定的bean名字在bean定義中有別名,則返回這些別名
     *
     * @param name
     * @return
     * @throws NoSuchBeanDefinitionException
     */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
        return applicationContext.getAliases(name);
    }

    /**
     * 判斷以給定名字註冊的bean定義是一個singleton還是一個prototype。
     * 如果與給定名字相應的bean定義沒有被找到,將會丟擲一個異常(NoSuchBeanDefinitionException)
     *
     * @param name
     * @return boolean
     * @throws NoSuchBeanDefinitionException
     */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
        return applicationContext.isSingleton(name);
    }

    /**
     * 如果BeanFactory包含一個與所給名稱匹配的bean定義,則返回true
     *
     * @param name
     * @return boolean
     */
    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    /**
     * 清除applicationContext靜態變數.
     */
    public static void cleanApplicationContext() {
        applicationContext = null;
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,請在applicationContext.xml中定義UtilsSpringContext");
        }
    }

    public static String getRootRealPath() {
        String rootRealPath = "";
        try {
            rootRealPath = getApplicationContext().getResource("").getFile().getAbsolutePath();
        } catch (IOException e) {
            //獲取系統根目錄失敗
        }
        return rootRealPath;
    }

    public static String getResourceRootRealPath() {
        String rootRealPath = "";
        try {
            rootRealPath = new DefaultResourceLoader().getResource("").getFile().getAbsolutePath();
        } catch (IOException e) {
            //獲取系統根目錄失敗
        }
        return rootRealPath;
    }

    @Override
    public void destroy() throws Exception {
        SpringBeanUtils.cleanApplicationContext();
    }

}

在spring.xml中新增以下部分,已獲取工具類bean例項:

<bean id="springBeanUtils" class="org.jiankunking.utils.SpringBeanUtils"/>

本文參考以下兩篇文章:
http://penghuaiyi.iteye.com/blog/2042296
http://www.tuicool.com/articles/numyuq

作者:jiankunking 出處:http://blog.csdn.net/jiankunking

相關文章