springmvc配置的全解析,致敬即将远去的mvc

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云解析 DNS,旗舰版 1个月
简介: springmvc配置的全解析,致敬即将远去的mvc


image.png

springmvc最为人称道的就是过多的xml配置,繁琐且复杂,本文将按照加载顺序逐一介绍配置,附上文件结构。

image.png

1.加载web.xml

启动时,第一步加载web.xml,初始化上线文与核心控制器DispatcherServlet 。

<?xml version="1.0" encoding="UTF-8"?>    
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
    xmlns="http://java.sun.com/xml/ns/javaee"    
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"    
    version="3.0">    
    <display-name>Archetype Created Web Application</display-name>    
    <welcome-file-list>    
        <welcome-file>/index.jsp</welcome-file>    
    </welcome-file-list>    
    <!-- 加载applicationContext.xml配置文件 -->    
    <context-param>    
         <param-name>contextConfigLocation</param-name>    
        <param-value>classpath:applicationContext.xml</param-value>    
    </context-param>    
    <!-- 创建WebApplicationContext(上下文) -->
    <listener>    
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    
    </listener>    
    <!-- 编码过滤器 -->    
    <filter>    
        <filter-name>encodingFilter</filter-name>    
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>    
        <async-supported>true</async-supported>    
        <init-param>    
            <param-name>encoding</param-name>    
            <param-value>UTF-8</param-value>    
        </init-param>    
    </filter>    
    <filter-mapping>    
        <filter-name>encodingFilter</filter-name>    
        <url-pattern>/*</url-pattern>    
    </filter-mapping>    
    <!-- 加载DispatcherServlet   -->    
    <servlet>    
        <servlet-name>SpringMVC</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>    
        <async-supported>true</async-supported>    
    </servlet>    
    <servlet-mapping>    
        <servlet-name>SpringMVC</servlet-name>    
        <url-pattern>/</url-pattern>    
    </servlet-mapping>    
</web-app> 

2.读取applicationContext.xml

之后,会读取 applicationContext.xml,该xml中引用了spring-dao.xml,spring-db.xml,spring-tx.xml。

<?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:tx="http://www.springframework.org/schema/tx"
  xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:websocket="http://www.springframework.org/schema/websocket"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd
                            http://www.springframework.org/schema/mvc 
                            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
                            http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd
                            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd                        
                            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
  <!-- 自动扫描 读取各个类的spring注解 并注入spring工厂中 使项目支持依赖注入 -->
  <context:component-scan base-package="com" />
  <!-- 导入DAO配置 -->
  <import resource="spring-dao.xml" />
  <!-- 导入数据库配置 -->
  <import resource="spring-db.xml" />
  <!-- 导入事务配置 -->
  <import resource="spring-tx.xml" />
</beans>

3.读取spring-dao.xml

mybatis配置,获取dao层所在的位置。

<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd
                            http://www.springframework.org/schema/mvc
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- DAO接口所在包名,Spring会自动查找其下的类 并且将所有的dao接口封装成beanDefinitions(spring bean) 装载进入spring factory -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--basePackage指定要扫描的包,在此包之下的映射器都会被搜索到。 可指定多个包,包与包之间用逗号或分号分隔-->
        <property name="basePackage" value="com.dao" />
        <!-- spring-db.xml中的 sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
</beans>

4.读取 spring-db.xml

这里是配置数据库连接与mybatis的相关配置。。

<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 引入配置文件  配置的数据库信息-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>
    <!-- 数据库连接池  -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>
    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件  将mapper.xml解析成SqlSessionFactoryBean并返回,在查询时
           可以获取SqlSessionFactory,并通过代理模调用到-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 引入mysql数据源 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:com/mappers/*.xml"></property>
    </bean>
</beans>

这里连接数据库需要知道数据库的账号密码,为了统一管理,将数据库配置放在jdbc.properties。

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mysql
username=root    
password=root    
initialSize=0    
maxActive=20    
maxIdle=20    
minIdle=1    
maxWait=60000   

5.读取spring-tx.xml

进行事务配置 通过applicationContext.xml读取的配置到这就结束了。

<?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:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
  <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
  <!-- 如果在同一个service类中定义的两个方法, 内层REQUIRES_NEW并不会开启新的事务,save和update中回滚都会导致整个事务的回滚 
    如果在不同的service中定义的两个方法, 内层REQUIRES_NEW会开启新的事务,并且二者独立,事务回滚互不影响 -->
  <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
  <!-- Spring编程式事务 -->
  <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
      <tx:method name="insertInto" propagation="REQUIRED"
        read-only="false" rollback-for="java.lang.Exception" />
    </tx:attributes>
  </tx:advice>
    <!-- 事务处理管理器 -->
  <bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 为spring-db.xml中dataSource数据库连接池 -->
    <property name="dataSource" ref="dataSource" />
  </bean>
</beans>

6.读取spring-mvc.xml

该配置主要是配置spring mvc核心功能,如aop,注解扫描位置,拦截器等。

<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc                   
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                        http://www.springframework.org/schema/task                   
                        http://www.springframework.org/schema/task/spring-task-3.0.xsd
                        http://www.springframework.org/schema/aop                        
                        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
  <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
  <bean id="mappingJacksonHttpMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes">
      <list>
        <value>text/html;charset=UTF-8</value>
      </list>
    </property>
  </bean>
  <!-- 添加注解驱动 -->
  <mvc:annotation-driven />
  <!-- 设置使用注解的类所在的包 mvc只需要扫描controller就可以-->
  <context:component-scan base-package="com.controller" />
  <!-- 完成请求和注解POJO的映射 -->
  <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
      <list>
        <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
      </list>
    </property>
  </bean>
  <!-- 定义跳转的文件的前后缀 ,视图模式配置 由于现在基本都是前后端分离 一般没什么软用 -->
  <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
  </bean>
  <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
  <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 默认编码 -->
    <property name="defaultEncoding" value="utf-8" />
    <!-- 文件大小最大值 -->
    <property name="maxUploadSize" value="10485760000" />
    <!-- 内存中的最大值 -->
    <property name="maxInMemorySize" value="40960" />
  </bean>
  <!-- aop的配置 -->
  <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  <!-- 定时任务配置 -->
  <task:executor id="executor" pool-size="10"
    queue-capacity="128" />
  <task:scheduler id="scheduler" pool-size="10" />
  <task:annotation-driven executor="executor"
    scheduler="scheduler" proxy-target-class="true" />
  <!-- 拦截器配置 -->
  <mvc:interceptors>
    <mvc:interceptor>
      <!--配置拦截器的作用路径 -->
      <mvc:mapping path="/**" />
      <!--定义在<mvc:interceptor>下面的表示匹配指定路径的请求才进行拦截 com.HandlerInterceptor为拦截器类名 -->
      <bean class="com.HandlerInterceptor" />
    </mvc:interceptor>
  </mvc:interceptors>
</beans>

7.拦截器类

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
@Component
public class HandlerInterceptor extends HandlerInterceptorAdapter {
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {
    System.out.println("11111111");
  }
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {
    System.out.println("222222222");
  }
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    System.out.println("333333333");
    return true;
  }
}

8.aop切面

import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Aspect
@Configuration
public class IntercepterInterface {
    private static final Logger LOG = LoggerFactory.getLogger(IntercepterInterface.class);
    @Pointcut("execution(* com.controller.*.*(..))")
    public void logPointCut() {
    }
    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        LOG.info("HTTP METHOD : " + request.getMethod());
        LOG.info("IP : " + request.getRemoteAddr());
        LOG.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName());
        System.out.println("aaa");
    }
    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    public void doAfterReturning(Object ret) throws Throwable {
        System.out.println("bbb");
    }
    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object ob = pjp.proceed();
        System.out.println("ccc");
        return ob;
    }
}


相关文章
|
26天前
|
负载均衡 算法 Java
Spring Cloud全解析:负载均衡算法
本文介绍了负载均衡的两种方式:集中式负载均衡和进程内负载均衡,以及常见的负载均衡算法,包括轮询、随机、源地址哈希、加权轮询、加权随机和最小连接数等方法,帮助读者更好地理解和应用负载均衡技术。
|
10天前
|
Java 对象存储 开发者
解析Spring Cloud与Netflix OSS:微服务架构中的左右手如何协同作战
Spring Cloud与Netflix OSS不仅是现代微服务架构中不可或缺的一部分,它们还通过不断的技术创新和社区贡献推动了整个行业的发展。无论是对于初创企业还是大型组织来说,掌握并合理运用这两套工具,都能极大地提升软件系统的灵活性、可扩展性以及整体性能。随着云计算和容器化技术的进一步普及,Spring Cloud与Netflix OSS将继续引领微服务技术的发展潮流。
24 0
|
24天前
|
XML 监控 Java
Spring Cloud全解析:熔断之Hystrix简介
Hystrix 是由 Netflix 开源的延迟和容错库,用于提高分布式系统的弹性。它通过断路器模式、资源隔离、服务降级及限流等机制防止服务雪崩。Hystrix 基于命令模式,通过 `HystrixCommand` 封装对外部依赖的调用逻辑。断路器能在依赖服务故障时快速返回备选响应,避免长时间等待。此外,Hystrix 还提供了监控功能,能够实时监控运行指标和配置变化。依赖管理方面,可通过 `@EnableHystrix` 启用 Hystrix 支持,并配置全局或局部的降级策略。结合 Feign 可实现客户端的服务降级。
101 23
|
7天前
|
存储 缓存 Java
在Spring Boot中使用缓存的技术解析
通过利用Spring Boot中的缓存支持,开发者可以轻松地实现高效和可扩展的缓存策略,进而提升应用的性能和用户体验。Spring Boot的声明式缓存抽象和对多种缓存技术的支持,使得集成和使用缓存变得前所未有的简单。无论是在开发新应用还是优化现有应用,合理地使用缓存都是提高性能的有效手段。
14 1
|
9天前
|
前端开发 Java Spring
关于spring mvc 的 addPathPatterns 拦截配置常见问题
关于spring mvc 的 addPathPatterns 拦截配置常见问题
|
2月前
|
持续交付 jenkins Devops
WPF与DevOps的完美邂逅:从Jenkins配置到自动化部署,全流程解析持续集成与持续交付的最佳实践
【8月更文挑战第31天】WPF与DevOps的结合开启了软件生命周期管理的新篇章。通过Jenkins等CI/CD工具,实现从代码提交到自动构建、测试及部署的全流程自动化。本文详细介绍了如何配置Jenkins来管理WPF项目的构建任务,确保每次代码提交都能触发自动化流程,提升开发效率和代码质量。这一方法不仅简化了开发流程,还加强了团队协作,是WPF开发者拥抱DevOps文化的理想指南。
49 1
|
2月前
|
缓存 Java 开发者
Spring高手之路22——AOP切面类的封装与解析
本篇文章深入解析了Spring AOP的工作机制,包括Advisor和TargetSource的构建与作用。通过详尽的源码分析和实际案例,帮助开发者全面理解AOP的核心技术,提升在实际项目中的应用能力。
23 0
Spring高手之路22——AOP切面类的封装与解析
|
2月前
|
Java 微服务 Spring
Spring Cloud全解析:配置中心之解决configserver单点问题
但是如果该configserver挂掉了,那就无法获取最新的配置了,微服务就出现了configserver的单点问题,那么如何避免configserver单点呢?
|
2月前
|
域名解析 网络协议 Linux
在Linux中,如何配置DNS服务器?
在Linux中,如何配置DNS服务器?
|
2月前
|
域名解析 网络协议 Linux
在Linux中,如何配置DNS服务器和解析服务?
在Linux中,如何配置DNS服务器和解析服务?

热门文章

最新文章

推荐镜像

更多
下一篇
无影云桌面