Spring獲取ApplicationContext


在Spring+Struts+Hibernate中,有時需要使用到Spring上下文。項目啟動時,會自動根據applicationContext配置文件初始化上下文,可以使用ApplicationContextAware接口去獲得Spring上下文。創建以下的類:

package com.school.tool;

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

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

}

在applicationContext配置文件中配置這個類:

<bean id="springContextUtil" class="com.school.tool.SpringContextUtil" />

這樣,在根據applicationContext初始化上下文時,會自動調用setApplicationContext()方法去獲取ApplicationContext。

也可以使用

ClassPathXmlApplicationContext("applicationContext.xml")

去獲取ApplicationContext,不過這相當於把重新初始化一次上下文,速度會很慢,而且逼格也不高,不推薦使用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM