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();
		}
	}
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值