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

Spring获取ApplicationContext

时间:2017-01-06 21:59:01      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:school   void   nts   except   cep   frame   getbean   stat   style   

在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,不过这相当于把重新初始化一次上下文,速度会很慢,而且逼格也不高,不推荐使用。

Spring获取ApplicationContext

标签:school   void   nts   except   cep   frame   getbean   stat   style   

原文地址:http://www.cnblogs.com/mstk/p/6257079.html

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