在B/S系统中得到spring的ApplicationContext对象的一点小技巧

在网上看了好多种得到spring的ApplicationContext对象的方法,在B/S系统,我们通常有时在整个系统中都需要这个对象去得到bean对象等等,但是看到很多人做的方法是将首先加载一次application.xml文件加载一次,后面又通过另外的出来为了得到applicationContext对象又去专门做个公共的类处理得到applicationContext对象,这样的话相当于把application.xml文件加载两次。为了解决这个加载两次的问题,有个小的技巧如下:

1:在我们的B/S系统中通常的配置是在web.xml文件中spring的监听

<!-- 定义Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

此时可以在添加配置监听的ContextLoaderListener类上做下手脚,我们去扩展这个类

 1 package com.kms.framework.core.utils.context;
 2 
 3 import javax.servlet.ServletContext;
 4 import javax.servlet.ServletContextEvent;
 5 
 6 import org.springframework.context.ApplicationContext;
 7 import org.springframework.web.context.support.WebApplicationContextUtils;
 8 
 9 public class ContextLoaderListener extends
10         org.springframework.web.context.ContextLoaderListener {
11 
12     //重写父类的contextInitialized方法    
13     @Override
14     public void contextInitialized(ServletContextEvent event) {
15         super.contextInitialized(event);
16         //通过这样得到ApplicationContext 
17         ServletContext context = event.getServletContext();
18         ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
19         //将ApplicationContext设置到自己定义的类中
20         ServiceLocator.setContext(ctx);
21     }
22 
23 }

ServiceLocator的代码如下:

package com.kms.framework.core.utils.context;

import com.kms.framework.core.exception.level.KmsException;
import com.kms.framework.core.exception.ExceptionKey;
import org.springframework.context.ApplicationContext;

public class ServiceLocator {

    /**
     * spring ApplicationContext
     */
    private static ApplicationContext context;
    
    protected ServiceLocator() { 
        
    }

    public static Object getBean(String beanName){
        try {
            return context.getBean(beanName);
        } catch (Exception e) {
            throw new KmsException(ExceptionKey.CONTEXT_LOAD_ERROR,e);
        }
    }
    
    /**
     * @return the context
     */
    public static ApplicationContext getContext() {
        return context;
    }
    /**
     * @param context the context to set
     */
    public static void setContext(ApplicationContext context) {
        ServiceLocator.context = context;
    }
}


2:此时web.xml的配置就变成了

<!-- 定义Spring监听器 -->
    <listener>
        <listener-class>com.kms.framework.core.utils.context.ContextLoaderListener</listener-class>
    </listener>

这样就在整个系统中通过ServiceLocator类的getContext()方法得到ApplicationContext对象了,这样就不必要加载两次spring的application.xml文件,做到了一举两得的效果

原文地址:https://www.cnblogs.com/working/p/3092700.html