zoukankan      html  css  js  c++  java
  • 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 

      1 package XXXX;
      2 
      3 import java.util.List;
      4 import java.util.Map;
      5 import java.util.Map.Entry;
      6 import java.util.Set;
      7 
      8 import javax.servlet.ServletContextEvent;
      9 import javax.servlet.ServletContextListener;
     10 
     11 import org.apache.log4j.Logger;
     12 import org.hibernate.CacheMode;
     13 import org.hibernate.Criteria;
     14 import org.hibernate.Session;
     15 import org.hibernate.SessionFactory;
     16 import org.springframework.aop.TargetSource;
     17 import org.springframework.aop.framework.Advised;
     18 import org.springframework.context.ApplicationContext;
     19 import org.springframework.orm.hibernate3.SessionFactoryUtils;
     20 import org.springframework.web.context.support.WebApplicationContextUtils;
     21 
     22 import xxx.BaseService;
     23 import xxx.ContextLoaderListener;
     24 
     25 /**
     26 * 获取Service
     27 * @author xxx
     28 * @time 2012-10-13 01:02:38
     29 * @version 1.0
     30 */
     31 public class ServiceLocator {
     32 
     33 private static final Logger _logger = Logger.getLogger(ServiceLocator.class);
     34 
     35 // 不允许实例化,全部使用static函数。
     36 private ServiceLocator() {
     37 }
     38 
     39 public static class Initializer implements ServletContextListener {
     40 public void contextInitialized(ServletContextEvent sce) {
     41 _logger.info("-加载Listener-:"+ServiceLocator.Initializer.class.getName());
     42 // 设置Spring的应用上下文
     43 APPLICATION_CONTEXT = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
     44 //数据缓存加载
     45 loadAllEntities();
     46 }
     47 public void contextDestroyed(ServletContextEvent sce) {
     48 }
     49 }
     50 
     51 private static ApplicationContext APPLICATION_CONTEXT;
     52 
     53 public static Object getService(String serviceId) {
     54 return APPLICATION_CONTEXT.getBean(serviceId);
     55 }
     56 
     57 public static <T> T getService(Class<T> serviceType) {
     58 if(APPLICATION_CONTEXT==null) return null;
     59 try{
     60 if(serviceType.toString().startsWith("interface")){
     61 return (T)APPLICATION_CONTEXT.getBean(serviceType);
     62 }else{
     63 //_logger.info("-不使用接口类获取bean将不能进入事务->" + serviceType.getName());
     64 }
     65 }catch (Exception e) {
     66 _logger.error(e);
     67 }
     68 String[] beanNames = APPLICATION_CONTEXT.getBeanDefinitionNames();
     69 for (int i = 0; i < beanNames.length; i++) {
     70 if (beanNames[i].indexOf("Service") == -1 && beanNames[i].indexOf("service") == -1) {
     71 continue;
     72 }
     73 T service = getService(beanNames[i], serviceType);
     74 if(service!=null){
     75 return service;
     76 }
     77 }
     78 _logger.info("-找不到对应Service->" + serviceType.getName());
     79 return null;
     80 }
     81 
     82 @SuppressWarnings("unchecked")
     83 public static <T> T getService(String serviceId, Class<T> serviceType) {
     84 try{
     85 if(serviceType.toString().startsWith("interface")){
     86 return (T)APPLICATION_CONTEXT.getBean(serviceId, serviceType);
     87 }else{
     88 //_logger.info("-不使用接口类获取bean将不能进入事务->" + serviceType.getName());
     89 }
     90 }catch (Exception e) {
     91 _logger.error(e);
     92 }
     93 Object obj = APPLICATION_CONTEXT.getBean(serviceId);
     94 if (obj instanceof Advised) {
     95 Advised a = (Advised) obj;
     96 TargetSource source = a.getTargetSource();
     97 try {
     98 T service = (T)source.getTarget();
     99 return service;
    100 } catch (Exception e) {
    101 //_logger.error("--", e);
    102 }
    103 }
    104 return null;
    105 }
    106 
    107 @SuppressWarnings("rawtypes")
    108 public static BaseService getServiceByEntityClass(Class entityClass) {
    109 return getServiceByEntityName(entityClass.getName());
    110 }
    111 
    112 @SuppressWarnings("rawtypes")
    113 public static BaseService getServiceByEntityName(String entityName) {
    114 Map<String, BaseService> map = APPLICATION_CONTEXT.getBeansOfType(BaseService.class);
    115 if(!map.isEmpty()){
    116 Set<Entry<String, BaseService>> set = map.entrySet();
    117 for (Entry<String, BaseService> entry : set) {
    118 BaseService service = entry.getValue();
    119 if (entityName.equals(service.getEntityName())) {
    120 return service;
    121 }
    122 }
    123 }
    124 _logger.info("-找不到对应Service-或没有实现BaseService接口->" + entityName);
    125 return null;
    126 }
    127 
    128 /**
    129 * 加载所有实体类到缓存中
    130 * @author xxx
    131 * @time: 2015年11月3日 18:27:19
    132 * @version: V1.0
    133 */
    134 private static void loadAllEntities(){
    135 SessionFactory sessionFactory = (SessionFactory)APPLICATION_CONTEXT.getBean("sessionFactory");
    136 Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    137 List<Class<?>> entities = ContextLoaderListener.getEntityClassList();
    138 session.setCacheMode(CacheMode.NORMAL);
    139 for (int i = 0; i < entities.size(); i++) {
    140 Class<?> clazz = entities.get(i);
    141 _logger.info("========数据缓存加载=========>"+clazz.getName());
    142 Criteria criteria = session.createCriteria(clazz);
    143 criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    144 criteria.setCacheable(true);
    145 criteria.list();
    146 }
    147 }
    148 }
  • 相关阅读:
    Nginx性能测试
    Centos 7.0设置/etc/rc.local无效问题解决
    Centos 7.0系统服务管理
    Centos 7.0设置静态IP
    importError:cannot import name imsave/imread等模块
    一位父亲写给儿子的信:今天你努力一点,比将来低头求人强100倍
    清华大学计算机学科推荐学术会议和期刊列表---人工智能与模式识别
    在使用python语言的open函数时,提示错误OSError: [Errno 22] Invalid argument: ‘文件路径’
    论文阅读笔记---HetConv
    typeerror: __init__() missing 2 required positional arguments: 'inputs' and 'outputs'
  • 原文地址:https://www.cnblogs.com/weixupeng/p/11159168.html
Copyright © 2011-2022 走看看