Spring MVC模式下,获取WebApplicationContext的工具类 方法
在已有的注解类型下,获取WebApplicationContext的工具类
通过 WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContextEvent sce);可以获得spring的单例webContext,这种方法是非常方便的,
如果涉及到底层架构师的级别,架设一套高可定制行的架构,使用泛型管理所有的Bean、service等类型非常有效果
好了,回归正题
WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContextEvent sce);
参数的sce怎么拿到的呢?
可以通过ServletContextListener 接口实现拿到,而ServletContextListener 中的方法只有下边两个,一个项目启动初始化环境时调用,一个项目摧毁关闭时调用,
其中,都可以刚给我们传递一个servletcontextevent这个请求上下文事件对象,我们可利用它来初始化一个WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContextEvent sce);中的sce对象,
这样就齐活了。
public interface ServletContextListener
extends EventListener
{
public abstract void contextInitialized(ServletContextEvent servletcontextevent);
public abstract void contextDestroyed(ServletContextEvent servletcontextevent);
}
具体使用如下,工具类ServiceLocator
package XXXX; import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; import org.apache.log4j.Logger;
import org.hibernate.CacheMode;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.Advised;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.web.context.support.WebApplicationContextUtils; import xxx.BaseService;
import xxx.ContextLoaderListener; /**
* 获取Service
* @author xxx
* @time 2012-10-13 01:02:38
* @version 1.0
*/
public class ServiceLocator { private static final Logger _logger = Logger.getLogger(ServiceLocator.class); // 不允许实例化,全部使用static函数。
private ServiceLocator() {
} public static class Initializer implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
_logger.info("-加载Listener-:"+ServiceLocator.Initializer.class.getName());
// 设置Spring的应用上下文
APPLICATION_CONTEXT = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
//数据缓存加载
loadAllEntities();
}
public void contextDestroyed(ServletContextEvent sce) {
}
} private static ApplicationContext APPLICATION_CONTEXT; public static Object getService(String serviceId) {
return APPLICATION_CONTEXT.getBean(serviceId);
} public static <T> T getService(Class<T> serviceType) {
if(APPLICATION_CONTEXT==null) return null;
try{
if(serviceType.toString().startsWith("interface")){
return (T)APPLICATION_CONTEXT.getBean(serviceType);
}else{
//_logger.info("-不使用接口类获取bean将不能进入事务->" + serviceType.getName());
}
}catch (Exception e) {
_logger.error(e);
}
String[] beanNames = APPLICATION_CONTEXT.getBeanDefinitionNames();
for (int i = 0; i < beanNames.length; i++) {
if (beanNames[i].indexOf("Service") == -1 && beanNames[i].indexOf("service") == -1) {
continue;
}
T service = getService(beanNames[i], serviceType);
if(service!=null){
return service;
}
}
_logger.info("-找不到对应Service->" + serviceType.getName());
return null;
} @SuppressWarnings("unchecked")
public static <T> T getService(String serviceId, Class<T> serviceType) {
try{
if(serviceType.toString().startsWith("interface")){
return (T)APPLICATION_CONTEXT.getBean(serviceId, serviceType);
}else{
//_logger.info("-不使用接口类获取bean将不能进入事务->" + serviceType.getName());
}
}catch (Exception e) {
_logger.error(e);
}
Object obj = APPLICATION_CONTEXT.getBean(serviceId);
if (obj instanceof Advised) {
Advised a = (Advised) obj;
TargetSource source = a.getTargetSource();
try {
T service = (T)source.getTarget();
return service;
} catch (Exception e) {
//_logger.error("--", e);
}
}
return null;
} @SuppressWarnings("rawtypes")
public static BaseService getServiceByEntityClass(Class entityClass) {
return getServiceByEntityName(entityClass.getName());
} @SuppressWarnings("rawtypes")
public static BaseService getServiceByEntityName(String entityName) {
Map<String, BaseService> map = APPLICATION_CONTEXT.getBeansOfType(BaseService.class);
if(!map.isEmpty()){
Set<Entry<String, BaseService>> set = map.entrySet();
for (Entry<String, BaseService> entry : set) {
BaseService service = entry.getValue();
if (entityName.equals(service.getEntityName())) {
return service;
}
}
}
_logger.info("-找不到对应Service-或没有实现BaseService接口->" + entityName);
return null;
} /**
* 加载所有实体类到缓存中
* @author xxx
* @time: 2015年11月3日 18:27:19
* @version: V1.0
*/
private static void loadAllEntities(){
SessionFactory sessionFactory = (SessionFactory)APPLICATION_CONTEXT.getBean("sessionFactory");
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
List<Class<?>> entities = ContextLoaderListener.getEntityClassList();
session.setCacheMode(CacheMode.NORMAL);
for (int i = 0; i < entities.size(); i++) {
Class<?> clazz = entities.get(i);
_logger.info("========数据缓存加载=========>"+clazz.getName());
Criteria criteria = session.createCriteria(clazz);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.setCacheable(true);
criteria.list();
}
}
}
Spring MVC模式下,获取WebApplicationContext的工具类 方法的更多相关文章
- Spring Mvc模式下Jquery Ajax 与后台交互操作
1.基本代码 1)后台控制器基本代码 @Controller @RequestMapping("/user") public class UserController { @Aut ...
- 【案例分享】使用ActiveReports报表工具,在.NET MVC模式下动态创建报表
提起报表,大家会觉得即熟悉又陌生,好像常常在工作中使用,又似乎无法准确描述报表.今天我们来一起了解一下什么是报表,报表的结构.构成元素,以及为什么需要报表. 什么是报表 简单的说:报表就是通过表格.图 ...
- Spring mvc 模式小结
http://www.taobaotesting.com/blogs/2375 1.spring mvc简介 Spring MVC框架是一个MVC框架,通过实现Model-View-Controlle ...
- Spring MVC源码——Servlet WebApplicationContext
上一篇笔记(Spring MVC源码——Root WebApplicationContext)中记录了下 Root WebApplicationContext 的初始化代码.这一篇来看 Servlet ...
- 【Spring】非Spring IOC容器下获取Spring IOC上下文的环境
前言 在Spring Web项目中,有些特殊的时候需要在非Spring IOC容器下获取Spring IOC容器的上下文环境,比如获取某个bean. 版本说明 声明POM文件,指定需引入的JAR. & ...
- MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB数据
看到下图,是通过Jqgrid实现表格数据的基本增删查改的操作.表格数据增删改是一般企业应用系统开发的常见功能,不过不同的是这个表格数据来源是非关系型的数据库MongoDB.nosql虽然概念新颖,但是 ...
- 卡卡游戏引擎之MVC模式下的事件处理
前言 在前一篇文章 卡卡游戏引擎快速入门中提到了卡卡游戏引擎采用mvc的开发模式,这里相信介绍一下引擎在mvc模式下是如何做到低耦合的事件处理的. 在卡卡编辑器中选择一个节点,然后在左侧工具栏中切换到 ...
- spring 获取 WebApplicationContext的几种方法
spring 获取 WebApplicationContext的几种方法 使用ContextLoader WebApplicationContext webApplicationContext = C ...
- Spring MVC源码——Root WebApplicationContext
目录 Spring MVC源码--Root WebApplicationContext 上下文层次结构 Root WebApplicationContext 初始化和销毁 ContextLoaderL ...
随机推荐
- QT一个最简单的openGL例子
创建一个基类为widget的工程 把文件夹glut64放到代码目录下,文件夹包含以下文件 freeglut.dll freeglut.lib glut.h freeglut.h freeglut_ex ...
- error LNK2019 : unresolved external symbol Zbar配置问题
原文链接:https://blog.csdn.net/MengchiCMC/article/details/77871714 出现error LNK2019 : unresolved external ...
- java 内部类(简单使用)
什么是内部类 1.内部类是指在一个外部类的内部再定义一个类. 2.内部类作为外部类的一个成员,依附于外部类而存在. 3.内部类可为静态,可用protected和private修饰(而外部类只能使用pu ...
- JDK8日期处理API(转)
转载地址:http://www.cnblogs.com/comeboo/p/5378922.html 转载地址:http://blog.csdn.net/hspingcc/article/detail ...
- Eclips的JDK更换为1.8
1.Window—Preferences—Java—Compiler—右侧面板设置为1.6 2.Window—Preferences—Java—Installed JREs—右侧面板“Add”本地的1 ...
- BZOJ 3143: [Hnoi2013]游走 概率与期望+高斯消元
Description 一个无向连通图,顶点从1编号到N,边从1编号到M.小Z在该图上进行随机游走,初始时小Z在1号顶点,每一步小Z以相等的概率随机选 择当前顶点的某条边,沿着这条边走到下一个顶点,获 ...
- 【UOJ#228】 基础数据结构练习题
题目描述 sylvia 是一个热爱学习的女孩子,今天她想要学习数据结构技巧. 在看了一些博客学了一些姿势后,她想要找一些数据结构题来练练手.于是她的好朋友九条可怜酱给她出了一道题. 给出一个长度为 n ...
- BZOJ 2651 城市改建 树形DP+模拟?
题意 给一颗树,删除一条边再加一条边,使它仍为一颗树且任意两点间的距离的最大值最小. 题目数据范围描述有问题,n为1或重建不能使任意两点距离最大值变小,可以输出任意答案. 分析 删除一条边后会使它变成 ...
- vue中全局组件与局部组件的注册,以及动态绑定props值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Python3:Collatz 序列(考拉咨猜想)
编写一个名为collatz()的函数,它有一个名为number的参数: 如果参数是偶数,那么collatz()就打印出number//2,并返回该值: 如果number是奇数,那么collatz()就 ...