Spring集成web环境(2)

ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
这里的spring配置文件名,因为写死了,所以耦合了,为了解耦的话,可以创建一个properties。
但是就这么一个地方就创建properties太浪费了,我么可以利用一下WEB-INF下的wen.xml进行配置,
我们可以利用全局初始化参数,把spring配置文件名放进去,然后通过读取xml从ServletContext域取出来。

           <!--全局初始化数据-->
            <context-param>
                <param-name>ContextConfigLocation</param-name>
                <param-value>applicationContext.xml</param-value>
            </context-param>

          //读取web.xml中的全局参数
String contextConfigLocation =    servletContext.getInitParameter("ContextConfigLocation");
ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);

这样以后如果需要改spring的配置名就可以直接去web.xml中改,而不需要改动代码

下面看一下Spring提供的应用上下文工具

 

 

1.导入spring监听器的工具包(spring-web)

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>

2.在web.xml中配置监听器

  <!--全局初始化数据-->
    <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>

3.使用WebApplicationContextUtils获得应用上下文对象ApplicationContext

WebApplicationContext app =   
        ApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService user = app.getBean(UserService.class);
        user.save();
posted @ 2022-03-21 09:15  长情c  阅读(34)  评论(0)    收藏  举报