spring服务定位器类

时间:2023-01-08 18:40:00

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

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

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

 package com.ims.common;

 import org.apache.log4j.Logger;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; /**
* 服务定位器
* 持有Spring的应用场景, 可在任何地方获取bean.
*/
public final class ServiceLocator implements ApplicationContextAware, DisposableBean { private static Logger logger = Logger.getLogger(ServiceLocator.class);
private static ApplicationContext context = null; /**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
* @param context
*/
@Override
public void setApplicationContext(ApplicationContext context) {
logger.debug("Injected the ApplicationContext into ServiceLocator:" + context);
if (ServiceLocator.context != null) {
logger.debug("[------------ ApplicationContext in the ServiceLocator " +
"is covered, as the original ApplicationContext is:"
+ ServiceLocator.context + " ------------]");
}
ServiceLocator.context = context;
} /**
* 实现DisposableBean接口,在Context关闭时清理静态变量.
*/
@Override
public void destroy() throws Exception {
ServiceLocator.clear();
} /**
* 取得存储在静态变量中的ApplicationContext.
* @return
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return context;
} /**
* 从Spring的应用场景中取得Bean, 自动转型为所赋值对象的类型.
* @param name bean名称
* @return bean对象
*/
@SuppressWarnings("unchecked")
public static <T> T getService(String name) {
assertContextInjected();
return (T) context.getBean(name);
} /**
* 从Spring的应用场景中取得Bean, 自动转型为所赋值对象的类型.
* @param requiredType bean类
* @return bean对象
*/
public static <T> T getService(Class<T> requiredType) {
assertContextInjected();
return context.getBean(requiredType);
} /**
* 清除ServiceLocator中的ApplicationContext
*/
public static void clear() {
logger.debug("Clear ApplicationContext in ServiceLocator :" + context);
context = null;
} /**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
if (context == null) {
throw new IllegalStateException("ApplicaitonContext not injected, " +
"as defined in the context.xml ServiceLocator");
}
}
}

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

 package com.ims.web;

 import javax.servlet.ServletContextEvent;

 import org.springframework.web.context.ContextLoaderListener;

 import com.ims.common.ServiceLocator;

 /**
* Spring场景加载监听器,用于加载/销毁Spring场景
*/
public class SpringContextLoaderListener extends ContextLoaderListener { private final ServiceLocator locator = new ServiceLocator(); public SpringContextLoaderListener() {
super();
} @Override
public void contextInitialized(ServletContextEvent event) {
super.contextInitialized(event); // 将Spring场景置入服务定位器中
locator.setApplicationContext(getCurrentWebApplicationContext());
} @Override
public void contextDestroyed(ServletContextEvent event) {
try {
locator.destroy();
}
catch (Exception e) {
e.printStackTrace();
} super.contextDestroyed(event);
}
}

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。

spring服务定位器类的更多相关文章

  1. Lind&period;DDD&period;IoC&lpar;大叔推荐&rpar;~在服务定位器中引入IoC容器~容器的适配器

    回到目录 关于依赖倒置(DIP) 高层模块不依赖于低层模块的实现,而低层模块依赖于高层模块定义的接口,通俗的讲,就是高层模块定义接口,低层模块负责实现,这在我们实际开发中经常被用到,层与层之间引用,经 ...

  2. YII框架的依赖注入容器与服务定位器简述

    依赖注入容器 依赖注入(Dependency Injection,DI)容器就是一个对象use yii\di\Container,它知道怎样初始化并配置对象及其依赖的所有对象. 依赖注入和服务定位器都 ...

  3. 服务定位器(Service Locator)

    服务定位器(Service Locator) 跟DI容器类似,引入Service Locator目的也在于解耦.有许多成熟的设计模式也可用于解耦,但在Web应用上, Service Locator绝对 ...

  4. 17、Spring Boot普通类调用bean【从零开始学Spring Boot】

    转载:http://blog.csdn.net/linxingliang/article/details/52013017 我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个 ...

  5. Java服务定位器模式

    当我们想要使用JNDI查找来定位各种服务时,使用服务定位器设计模式. 考虑到为服务查找JNDI的高成本,所以在服务定位器模式使用缓存技术. 首次需要服务时,服务定位器在JNDI中查找并缓存服务对象. ...

  6. 避免在ASP&period;NET Core中使用服务定位器模式

    (此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:服务定位器(Service Locator)作为一种反模式,一般情况下应该避免使用,在 ...

  7. Spring Boot普通类调用bean

    1 在Spring Boot可以扫描的包下 假设我们编写的工具类为SpringUtil. 如果我们编写的SpringUtil在Spring Boot可以扫描的包下或者使用@ComponentScan引 ...

  8. Android - 位置定位&lpar;Location&rpar;服务&lpar;Service&rpar;类的基本操作

    位置定位(Location)服务(Service)类的基本操作 本文地址: http://blog.csdn.net/caroline_wendy 定位服务(Location Service),能够确 ...

  9. Spring &commat;Aspect进行类的接口扩展

    Spring @Aspect进行类的接口扩展: XML: <?xml version="1.0" encoding="UTF-8"?> <be ...

随机推荐

  1. android获取textview的行数

    最近项目需求,需要获取Textview的行数,通过行数与TextView的maxLines进行比较来确定是否显示TextView下方的展开按钮是否显示,废话少说直接上代码,mTextView.getL ...

  2. python unicode转中文及转换默认编码

    一. 在爬虫抓取网页信息时常需要将类似"\u4eba\u751f\u82e6\u77ed\uff0cpy\u662f\u5cb8"转换为中文,实际上这是unicode的中文编码.可 ...

  3. setProgressBarIndeterminateVisibility&lpar;true&rpar;&semi;

    此为在标题栏 上 设置一个loading 圈  实用...

  4. Jmeter操作手册

    以前没有发pdf的版本,我现在把pdf版本放在百度网盘里面了,需要的童鞋可以去下载:http://pan.baidu.com/s/1bp43jeJ Ksudi Jmeter操作指南 简要说明 Beck ...

  5. IIS7&sol;8 HTTP Error 500&period;19 错误 0x80070021

    IIS7.0/8.0的错误HTTP Error 500.19 - Internal Server Error ,错误代码为0x80070021,大概原因为IIS7.0的安全设定相比前版本有很大的变更. ...

  6. Mvc里删除Cooki

    /// <summary> /// 删除Cookie /// </summary> /// <param name="skuID">从购物车选择 ...

  7. jbpm系列之五--使用decision节点判断分支情况

    我们在用JBPM做流程的时候,很多时候会遇到需要判断的节点.类似java中的switch,根据不同的状态,跳转到不同的节点. 首先我们定义一个流程信息,jpdl流程图如下 明显的可以看到,在此种情况下 ...

  8. 多线程简单实例(1)真的需要synchronized么?

    说道多线程的安全问题,很多人想到就就是加锁.用到synchronized关键字. 那就要先说说synchronized问什么能够保证线程安全了. 首先要了解线程的工作方式:线程工作分为工作内存和主内存 ...

  9. Linux下SVN提交时强制写日志

    Linux版本: 1.在svn的hooks目录下新建一个名为pre-commit的文件并为其添加执行权限(用vi pre-commit直接创建) 2.pre-commit文件的内容如下: #!/bin ...

  10. 2016 USP-ICMC-Codeforces-Gym101063C-Sleep Buddies Gym101063F-Bandejao Gym101063J-The Keys

    Gym101063C-Sleep Buddies It is nighttime in the Earth Colony on Mars and everyone is getting ready t ...