zoukankan      html  css  js  c++  java
  • 普通Java类获取Spring的ApplicationContext

    在SSH集成的前提下。某些情况我们需要在Action以外的类中来获得SPRing所管理的Service对象。


    之前我在网上找了好几好久都没有找到合适的方法。例如:

    ApplicationContext context = new ClassPathXmlApplicationContext();

    当时我觉得没有这个必要,浪费内存。后来我终于想出了一个解决方法。在此拿来给大家参考下,希望对大家有帮助。

    1.创建一个类并让其实现org.springframework.context.ApplicationContextAware接口来让Spring在启动的时候为我们注入ApplicationContext对象.

        示例代码:


             view plaincopy to clipboardprint?
    import org.springframework.beans.BeansException;  
      import org.springframework.context.ApplicationContext;  
      import org.springframework.context.ApplicationContextAware;  
     
     
     
    ublic class MyApplicationContextUtil implements ApplicationContextAware {  
    private static ApplicationContext context;//声明一个静态变量保存  
    @Override 
    public void setApplicationContext(ApplicationContext contex)  
      throws BeansException {  
    this.context=contex;  
    }  
    public static ApplicationContext getContext(){  
    return context;  
    }  
    import org.springframework.beans.BeansException;
       import org.springframework.context.ApplicationContext;
       import org.springframework.context.ApplicationContextAware;

    public class MyApplicationContextUtil implements ApplicationContextAware {
    private static ApplicationContext context;//声明一个静态变量保存
    @Override
    public void setApplicationContext(ApplicationContext contex)
       throws BeansException {
      this.context=contex;
    }
    public static ApplicationContext getContext(){
      return context;
    }
    }

    2.在applicationContext.xml文件中配置此bean,以便让Spring启动时自动为我们注入ApplicationContext对象.

           例:

               <!-- 这个bean主要是为了得到ApplicationContext 所以它不需要其它属性-->
               <bean class="org.ing.springutil.MyApplicationContextUtil"></bean>

    3.有了这个ApplicationContext之后我们就可以调用其getBean("beanName")方法来得到由Spring 管理所有对象.

    ----------------结束------------

  • 相关阅读:
    JMeter之录制脚本
    好的软件测试人员简历是什么样子的?
    好的软件测试人员简历是什么样子的?
    luogu P2002 消息扩散
    luogu P1726 上白泽慧音
    luogu P1038 神经网络
    luogu P1418 选点问题
    luogu P1824 进击的奶牛
    luogu P1330 封锁阳光大学
    luogu P1546 最短网络 Agri-Net
  • 原文地址:https://www.cnblogs.com/skrifer/p/ssh.html
Copyright © 2011-2022 走看看