spring服务定位器类

此文章是基于  搭建Jquery+SpringMVC+Spring+Hibernate+MySQL平台

功能:通过持有的Spring应用场景ApplicationContext,可在任何地方获取bean。

1. 服务定位器类:ServiceLocator.java

 1 package com.ims.common;
 2 
 3 import org.apache.log4j.Logger;
 4 import org.springframework.beans.factory.DisposableBean;
 5 import org.springframework.context.ApplicationContext;
 6 import org.springframework.context.ApplicationContextAware;
 7 
 8 /**
 9  * 服务定位器
10  * 持有Spring的应用场景, 可在任何地方获取bean.
11  */
12 public final class ServiceLocator implements ApplicationContextAware, DisposableBean {
13     
14     private static Logger logger = Logger.getLogger(ServiceLocator.class);
15     private static ApplicationContext context = null;
16     
17     /**
18      * 实现ApplicationContextAware接口, 注入Context到静态变量中.
19      * @param context
20      */
21     @Override
22     public void setApplicationContext(ApplicationContext context) {        
23         logger.debug("Injected the ApplicationContext into ServiceLocator:" + context);
24         if (ServiceLocator.context != null) {
25             logger.debug("[------------ ApplicationContext in the ServiceLocator " +
26                                 "is covered, as the original ApplicationContext is:"
27                                             + ServiceLocator.context + " ------------]");
28         }
29         ServiceLocator.context = context; 
30     }
31     
32     /**
33      * 实现DisposableBean接口,在Context关闭时清理静态变量.
34      */
35     @Override
36     public void destroy() throws Exception {
37         ServiceLocator.clear();
38     }
39     
40     /**
41      * 取得存储在静态变量中的ApplicationContext.
42      * @return
43      */
44     public static ApplicationContext getApplicationContext() {
45         assertContextInjected();
46         return context;
47     }
48     
49     /**
50      * 从Spring的应用场景中取得Bean, 自动转型为所赋值对象的类型.
51      * @param name bean名称
52      * @return bean对象
53      */
54     @SuppressWarnings("unchecked")
55     public static <T> T getService(String name) {
56         assertContextInjected();
57         return (T) context.getBean(name);
58     }
59     
60     /**
61      * 从Spring的应用场景中取得Bean, 自动转型为所赋值对象的类型.
62      * @param requiredType bean类
63      * @return bean对象
64      */
65     public static <T> T getService(Class<T> requiredType) {
66         assertContextInjected();
67         return context.getBean(requiredType);
68     }
69     
70     /**
71      * 清除ServiceLocator中的ApplicationContext
72      */
73     public static void clear() {
74         logger.debug("Clear ApplicationContext in ServiceLocator :" + context);
75         context = null;
76     }
77     
78     /**
79      * 检查ApplicationContext不为空.
80      */
81     private static void assertContextInjected() {
82         if (context == null) {
83             throw new IllegalStateException("ApplicaitonContext not injected, " +
84                             "as defined in the context.xml ServiceLocator");
85         }
86     }
87 }
View Code


2. Spring上下文场景加载监听器:SpringContextLoaderListener.java

 1 package com.ims.web;
 2 
 3 import javax.servlet.ServletContextEvent;
 4 
 5 import org.springframework.web.context.ContextLoaderListener;
 6 
 7 import com.ims.common.ServiceLocator;
 8 
 9 /**
10  * Spring场景加载监听器,用于加载/销毁Spring场景
11  */
12 public class SpringContextLoaderListener extends ContextLoaderListener {
13     
14     private final ServiceLocator locator = new ServiceLocator();
15     
16     public SpringContextLoaderListener() {
17         super();
18     }
19     
20 
21     @Override
22     public void contextInitialized(ServletContextEvent event) {
23         super.contextInitialized(event);
24         
25         // 将Spring场景置入服务定位器中
26         locator.setApplicationContext(getCurrentWebApplicationContext());                
27     }
28     
29     
30     @Override
31     public void contextDestroyed(ServletContextEvent event) {
32         try {
33             locator.destroy();
34         } 
35         catch (Exception e) {
36             e.printStackTrace();
37         }        
38         
39         super.contextDestroyed(event);            
40     }
41 }
View Code


3. 修改 web.xml

如果存在如下代码,则去掉

<listener>   
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
  </listener>

然后添加上如下代码:

<listener>
     <listener-class>com.ims.web.SpringContextLoaderListener</listener-class>
  </listener>


4. 在 src/applicationContext.xml 中添加如下代码:

<bean class="com.ims.common.ServiceLocator"/>


5. 调用 ServiceLocator.java 中的 getService 函数,可分为按名称或类型获取bean。

原文地址:https://www.cnblogs.com/Mr-kevin/p/5560470.html