Spring 框架学习(二):Spring 应用配置文件讲解
2017-10-22 10:29
411 查看
Spring 框架学习二Spring 应用配置文件解析
webxml
applicationContextxml
mvcxml
参考资料
context-param 节点存储的键值对会被存入 ServletContext 中,后续可以通过其 getInitParameter 得到其值,
listener 节点存放的 ContextLoaderListene 类实现了接口 ServletContextListener,会监听 Web 容器的初始化和关闭,做相应的初始化和销毁工作:
Spring 容器就是在 ContextLoaderListener 的 contextInitialized 方法中被初始化:
listener 节点存放的另一个类 RequestContextListener 实现了接口 ServletRequestListener,会监听每次 HTTP 请求,管理作用域为 Request 的 bean。对于作用域为 request 的 bean,就会在请求进来的时候创建,结束的时候销毁。
这其中 ContextLoaderListener 是必须的,RequestContextListener 是可选的。
servlet 节点用于配置处理 HTTP 请求的 HttpServlet 实现类,具体处理哪些请求是配置在 servlet-mapping 里的。DispatcherServlet 实现的是 MVC 模式中的控制器,负责分发请求。所有的 Web 请求都需要经过它来处理,进行转发、匹配、数据处理后,转由页面进行呈现。在初始化时会解析 contextConfigLocation 参数配置的文件,建立 MVC 子容器。
filter 节点配置过滤器 Filter,可以对 HTTP 请求做一些过滤、校验、日志监控记录的工作,具体适配的请求 url 配置在 filter-mapping 节点。
我有一个疑问,为什么要在 component-scan 里 exclude 掉 Controller 呢?这是因为 Spring 核心模块并不处理 HTTP 请求,处理 HTTP 请求的是 Spring MVC 子模块,两者使用的是不同的容器:Spring Context 父容器和 Spring MVC 子容器。Controller 注解的 bean 要在 mvc 容器中创建才能起到作用,所以要在父容器的配置中排除掉。
在 《Spring 技术内幕》这本书中提到“IOC 容器会首先向其双亲上下文去 getBean”,这跟我们日常运行程序的感受不符,所以到底是先去父容器拿 bean 还是先去子容器拿 bean,我们还是深入源码看看吧。ApplicationContext 的 getBean 方法实现在 AbstractApplicationContext 类:
该方法调用了 BeanFactory 的 getBean 方法,从 AbstractBeanFactory 类的 getBean 方法中看到,的确是优先使用子容器的 bean:
此处的 component-scan 中要排除掉 Service 注解,那么如果不排除会有什么问题吗?多数情况下也不会有问题,但是如果你用到了 AOP,那么由于这里没有排除 Service 注解,Controller 用到的 Service 既会出现在父容器,也会出现在子容器,但是只有父容器中的 Service 会被 AOP 处理,然而 Controller 优先使用同一个容器中的 Service,就会导致其调用了没有被 AOP 代理的服务。
总结一下,mvc.xml 里存放的基本都是跟处理 HTTP 请求相关的配置。
webxml
applicationContextxml
mvcxml
参考资料
Spring 框架学习(二):Spring 应用配置文件解析
初学 Spring 的时候,只是照猫画虎,对于每一项配置的由来并不十分了解。这里,我们深入了解一下,这些配置都起到了什么作用?web.xml
应用启动的时候,Tomcat 容器会读取 web.xml 配置文件,一个正常的 web.xml 示例如下:<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.gif</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <filter> <filter-name>http_filter</filter-name> <filter-class>com.xxx.HttpFilter</filter-class> </filter> <filter-mapping> <filter-name>http_filter</filter-name> <url-pattern>/api/search.json</url-pattern> </filter-mapping> </web-app>
context-param 节点存储的键值对会被存入 ServletContext 中,后续可以通过其 getInitParameter 得到其值,
ServletContext sc; String configLocationParam = sc.getInitParameter("contextConfigLocation");
listener 节点存放的 ContextLoaderListene 类实现了接口 ServletContextListener,会监听 Web 容器的初始化和关闭,做相应的初始化和销毁工作:
public interface ServletContextListener extends EventListener { void contextInitialized(ServletContextEvent var1); void contextDestroyed(ServletContextEvent var1); }
Spring 容器就是在 ContextLoaderListener 的 contextInitialized 方法中被初始化:
public class ContextLoaderListener extends ContextLoader implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { this.contextLoader = this.createContextLoader(); if(this.contextLoader == null) { this.contextLoader = this; } this.contextLoader.initWebApplicationContext(event.getServletContext()); } }
listener 节点存放的另一个类 RequestContextListener 实现了接口 ServletRequestListener,会监听每次 HTTP 请求,管理作用域为 Request 的 bean。对于作用域为 request 的 bean,就会在请求进来的时候创建,结束的时候销毁。
public interface ServletRequestListener extends EventListener { void requestDestroyed(ServletRequestEvent var1); void requestInitialized(ServletRequestEvent var1); }
这其中 ContextLoaderListener 是必须的,RequestContextListener 是可选的。
servlet 节点用于配置处理 HTTP 请求的 HttpServlet 实现类,具体处理哪些请求是配置在 servlet-mapping 里的。DispatcherServlet 实现的是 MVC 模式中的控制器,负责分发请求。所有的 Web 请求都需要经过它来处理,进行转发、匹配、数据处理后,转由页面进行呈现。在初始化时会解析 contextConfigLocation 参数配置的文件,建立 MVC 子容器。
filter 节点配置过滤器 Filter,可以对 HTTP 请求做一些过滤、校验、日志监控记录的工作,具体适配的请求 url 配置在 filter-mapping 节点。
applicationContext.xml
ContextLoaderListener 会解析 applicationContext.xml 文件来初始化 Spring 容器。常见的配置示例如下:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-autowire="byName"> <!-- 加载参数配置 --> <context:property-placeholder location="classpath:config.properties" ignore-unresolvable="true"/> <!-- 自动扫描 web 包 ,将带有注解的类 纳入 spring 容器管理 --> <context:component-scan base-package="com.xxx.web"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 创建 bean --> <bean id="httpClient" class="com.xxx.http.HttpClient"/> <!-- 声明自动为spring容器中那些配置 @AspectJ 切面的 bean 创建代理 --> <aop:aspectj-autoproxy/> <!-- 加载其他配置文件,import 的使用使得配置文件也可以模块化 --> <import resource="classpath:xxx.xml"/> </beans>
我有一个疑问,为什么要在 component-scan 里 exclude 掉 Controller 呢?这是因为 Spring 核心模块并不处理 HTTP 请求,处理 HTTP 请求的是 Spring MVC 子模块,两者使用的是不同的容器:Spring Context 父容器和 Spring MVC 子容器。Controller 注解的 bean 要在 mvc 容器中创建才能起到作用,所以要在父容器的配置中排除掉。
在 《Spring 技术内幕》这本书中提到“IOC 容器会首先向其双亲上下文去 getBean”,这跟我们日常运行程序的感受不符,所以到底是先去父容器拿 bean 还是先去子容器拿 bean,我们还是深入源码看看吧。ApplicationContext 的 getBean 方法实现在 AbstractApplicationContext 类:
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext, DisposableBean { public <T> T getBean(Class<T> requiredType) throws BeansException { return this.getBeanFactory().getBean(requiredType); } }
该方法调用了 BeanFactory 的 getBean 方法,从 AbstractBeanFactory 类的 getBean 方法中看到,的确是优先使用子容器的 bean:
public Object getBean(String name) throws BeansException { return this.doGetBean(name, (Class)null, (Object[])null, false); } protected <T> T doGetBean(String name, Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = this.transformedBeanName(name); Object sharedInstance = this.getSingleton(beanName); Object bean; if(sharedInstance != null && args == null) { // 省略 } else { if(this.isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } BeanFactory ex = this.getParentBeanFactory(); // containsBeanDefinition 返回 false,即当前容器不存在 bean,才去父容器获取 if(ex != null && !this.containsBeanDefinition(beanName)) { String var21 = this.originalBeanName(name); if(args != null) { return ex.getBean(var21, args); } return ex.getBean(var21, requiredType); } // 省略其他。。。 } private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap(); // 此方法在 DefaultListableBeanFactory 类中 public boolean containsBeanDefinition(String beanName) { Assert.notNull(beanName, "Bean name must not be null"); return this.beanDefinitionMap.containsKey(beanName); }
mvc.xml
spring mvc 子容器初始化依赖 mvc.xml,此文件具体名称是和 DispatcherServlet 配置在一起的参数。<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 扫描 Controller --> <context:component-scan base-package="com.xxx.controller" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> <!-- HTTP 请求适配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <!-- 使用 Jackson 的 ObjectMapper 读取/编写 JSON 数据。它转换媒体类型为 application/json 的数据。 --> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean> <!-- 配置 velocity 引擎 --> <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <property name="resourceLoaderPath" value="/WEB-INF/views/vm/" /> <property name="configLocation" value="classpath:velocity.properties" /> </bean> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="ignoreAcceptHeader" value="true"/> <property name="mediaTypes"> <map> <entry key="json" value="application/json" /> <entry key="xml" value="application/xml" /> <entry key="jsonp" value="application/javascript" /> </map> </property> <property name="favorParameter" value="false"/> <property name="viewResolvers"> <list> <!-- vm 视图解析器 --> <bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property name="suffix" value=".vm" /> </bean> <!-- jsp 视图处理器 --> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" /> </list> </property> <property name="defaultViews"> <list> <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> </list> </property> </bean> <mvc:interceptors> <mvc:interceptor> <!-- 对所有的请求使用 CommonInterceptor 处理 --> <mvc:mapping path="/**" /> <bean class="com.xxx.web.interceptor.CommonInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> </beans>
此处的 component-scan 中要排除掉 Service 注解,那么如果不排除会有什么问题吗?多数情况下也不会有问题,但是如果你用到了 AOP,那么由于这里没有排除 Service 注解,Controller 用到的 Service 既会出现在父容器,也会出现在子容器,但是只有父容器中的 Service 会被 AOP 处理,然而 Controller 优先使用同一个容器中的 Service,就会导致其调用了没有被 AOP 代理的服务。
总结一下,mvc.xml 里存放的基本都是跟处理 HTTP 请求相关的配置。
参考资料
关于XML文档的xmlns、xmlns:xsi和xsi:schemaLocation相关文章推荐
- java开源框架应用技巧之spring配置文件中如果有多个.hbm.xml文件的话,无论是项目开发过程中还是维护过程中修改起来都会很麻烦切容易出错
- Java框架spring 学习笔记(十八):事务管理(xml配置文件管理)
- spring 学习--beans.xml配置文件的讲解
- Spring 学习日记 (四) Spring 整合Mybaits 和 struts2 框架的配置文件
- 学习三大框架Struts2 、 Hibernate 、 Spring时,涉及到三大框架的配置文件以及整合。
- MVC设计模式/SpringMVC/SSM框架整合配置文件讲解
- pyramid框架学习之(二)——应用的配置文件
- spring基础学习二(配置文件)
- 在weblogic下部署web应用,加载spring配置文件时要删除注释
- 框架学习之Spring 第一节 认识Spring以及环境的配置
- Spring视频学习(十七)Spring配置文件总结
- SSH框架学习语录二:关注框架都有的xml配置文件和反射
- 工作流Activiti的学习总结(四)Spring和Activiti的整合配置讲解
- Spring学习笔记 在XML配置文件中使用properties文件的键值
- 框架学习之Spring 第一节 认识Spring以及环境的配置
- 服务器集群管理框架从构思到完成(三)高级应用示例:修改远程windows和linux服务器配置文件
- 深入浅出学习Struts1框架(七):ActionServlet实例化之读取struts-config.xml配置文件
- Portal-Basic Web 应用开发框架:应用篇(一) —— 配置文件
- spring mvc框架 web.xml配置文件 Could not open ServletContext resource [/WEB-INF/classes/spring-servlet.xml] 错误
- SSH框架学习语录三:Struts2+Spring, 将框架的配置文件整合起来