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