Spring集成web环境

Spring集成web环境

标签(空格分隔): Spring


ApplicationContext应用上下文获取方式

    应用上下文对象时通过newClasspathXmlApplicationContext(spring配置文件)方式获取的,但每次从容器中获得Bean时都要编写newClasspathXmlApplicationContext(spring配置文件),这样的弊端是配置文件加载多次,应用上下文对象创建多次

    在web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,在将其存储到最大的域servletContext域中,这样就可以在任意位置从域中获得应用上下文ApplicationContext对象了。

此处输入图片的描述


Spring提供获取应用上下文的工具

    Spring提供了一个监听器ContextLoaderListener实现了对以下`功能`的封装,该监听器内部加载Spring配置文件,创建应用上下文对象考虑,并转存到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获得应用上下文对象。

实现原理:

  1. 通过一个监听器Listener使得Web项目在启动时就直接在Context域中加载Spring容器,从而使得全局只加载一次,减少重复加载
public class ContextLoaderListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext  servletContext = servletContextEvent.getServletContext();
        //读取web.xml中的全局参数

        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");


        ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
        //将Spring的应用上下文对象存储到ServletContext域中
        servletContext.setAttribute("app",app);
        System.out.println("spring容器创建完毕...");
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
  1. 在通过一个WebApplicationContextUtils来实现获得应用上下文对象,从而使得获取的实现不需要记住Attribute中的别名
public class WebApplicationContextUtils {
    public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
        return (ApplicationContext)servletContext.getAttribute("app");
    }
}

所以我们需要做的只有两件事:

  1. 在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)
  2. 使用WebApplicationContextUtils获得应用上下文对象ApplicationContext

Spring集成web环境步骤:

  1. 配置ContextLoaderlistener监听器
    <!--全局初始化参数-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

  1. 使用WebApplicationContextUtils获得应用上下文
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
        ServletContext servletContext = this.getServletContext();
        WebApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService =  app.getBean(UserService.class);
        userService.save();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值