1. 程式人生 > >Java普通類獲取Bean工具類

Java普通類獲取Bean工具類

       Spring中提供一些Aware相關介面,像是BeanFactoryAware、 ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等,例項這些 Aware介面的Bean在被初始之後,可以取得一些相對應的資源,例如例項BeanFactoryAware的Bean在初始後,Spring容器將會注入BeanFactory的例項,而例項ApplicationContextAware的Bean,在Bean被初始後,將會被注入 ApplicationContext的例項等等。

第一步:編寫工具類

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

public class BeanUtil implements ApplicationContextAware {
	/** Spring上下文 */
    private static ApplicationContext applicationContext;
    
    /**
     * 根據beanName獲取物件
     *
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }
 
    public static <T> T getBean(String beanName, Class<T> clazz) {
        return clazz.cast(getBean(beanName));
    }
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.applicationContext = applicationContext;
    }
}

第二步:

在applicationContext.xml中建立第一步工具類Bean

<bean id="beanUtil" class="BeanUtil路徑"></bean>

OK,百試不爽!