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

  • 相关阅读:
    python版本升级及pip部署方法
    Redis集群管理(二)
    UP UP UP!(dp)
    One Way Roads(搜索)
    Back to Underworld(搜索)
    队列链表实现以及有序表的合并
    第八届郑州轻工业学院ACM(程序设计大赛)校内预选赛
    Modulo Sum(背包 + STL)
    Co-prime Array&&Seating On Bus(两道水题)
    Hard Process(二分)
  • 原文地址:https://www.cnblogs.com/mstk/p/6257079.html
Copyright © 2011-2022 走看看