spring实例化类,避免重复加载applicationcontext

来源:互联网 发布:域名证书有什么用 编辑:程序博客网 时间:2024/06/16 07:42

之前用spring,项目中都是用工厂类去获取注入的类,代码是这样的:

IInterceptor interceptor = (IInterceptor)BeanFactory.getInstance("interceptorRedirect");

在BeanFactory中会加载整个applicationcontext文件
/** * 初始化Spring容器 * @param * @return */public static void init() {if (logger.isDebugEnabled()) {logger.debug("init() - start");}cxt = new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");if (logger.isDebugEnabled()) {logger.debug("init() - end");}}

但是问题来了,我只想用某一个类,applicationContext中那么对配置,很多都是没必要的,而且每获取一次就加载一边,效率肯定很慢啊。

解决这个办法的思路是:启动项目时加载整个applicationContext文件,加载完之后保存下applicationContext实例,然后从这个实例里面取得注入的类
步骤1:创建SystemApplicationContext类用于保存applicationContext实例。

步骤2:创建类继承ContextLoaderListener。

public class ContextLoaderListenerBean extends ContextLoaderListener {@Overridepublic void contextInitialized(ServletContextEvent event) {        ServletContext context = event.getServletContext();           super.contextInitialized(event);           ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);           SystemApplicationContext.setCtx(ctx);}

步骤3:修改web.xml

<listener>          <listener-class>com.bonc.common.ContextLoaderListenerBean</listener-class>  </listener> 

重新启动,然后调用的时候就这样调用:

IInterceptor interceptor = (IInterceptor) SystemApplicationContext.getCtx().getBean("interceptorRedirect");


0 0
原创粉丝点击