为什么需要整合SpringMVC

Spring和Mybatis以前已经整合过,这样能够更加方便的使用Mybatis,但为什么还需要整合SpringMVC呢?SpringMVC不是已经属性Spring的一部分了吗?为什么还需要整合?
是需要整合的,因为现在所有的Bean都在同一个容器里面。我们通常在Controller层调用Service层,Service层调用Dao层,如果在Service层也调用Controller层的代码,比如在Service层里面注入Controller,代码就会变得混乱。为了解决这个问题,我们需要从代码层面进行隔离,如果Controller层的代码放在一个容器、Service层的代码放在另一个容器里面,彼此容器相互隔离就好了,于是父子容器的方案就诞生啦。

相关准备和依赖

在实现父子容器方案前,我们需要对项目做准备工作

模型数据

  1. package com.lff.domain;
  2. public class Customer {
  3. private Integer custId;
  4. private String custName;
  5. private String custAddress;
  6. private String custCity;
  7. private String custState;
  8. private String custZip;
  9. private String custCountry;
  10. private String custContact;
  11. private String custEmail;
  12. //getter setter
  13. }

Dao层

  1. package com.lff.dao;
  2. import com.lff.domain.Customer;
  3. import org.apache.ibatis.annotations.Select;
  4. import java.util.List;
  5. public interface CustomerDao {
  6. Boolean save(Customer customer);
  7. Boolean update(Customer customer);
  8. List<Customer> list();
  9. Customer get(Integer id);
  10. Boolean remove(Integer id);
  11. }

Service层

  1. package com.lff.service;
  2. import com.lff.domain.Customer;
  3. import java.util.List;
  4. public interface CustomerService {
  5. Boolean save(Customer customer);
  6. Boolean update(Customer customer);
  7. List<Customer> list();
  8. Customer get(Integer id);
  9. }

实现类

  1. package com.lff.service.impl;
  2. import com.lff.dao.CustomerDao;
  3. import com.lff.domain.Customer;
  4. import com.lff.service.CustomerService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Component;
  7. import java.util.List;
  8. @Component
  9. public class CustomerServiceImpl implements CustomerService {
  10. @Autowired
  11. CustomerDao customerDao;
  12. @Override
  13. public Boolean save(Customer customer) {
  14. return customerDao.save(customer);
  15. }
  16. @Override
  17. public Boolean update(Customer customer) {
  18. return customerDao.update(customer);
  19. }
  20. @Override
  21. public List<Customer> list() {
  22. return customerDao.list();
  23. }
  24. @Override
  25. public Customer get(Integer id) {
  26. return customerDao.get(id);
  27. }
  28. }

Controller层

  1. package com.lff.controller;
  2. import com.lff.domain.Customer;
  3. import com.lff.service.CustomerService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import java.util.List;
  9. @Controller
  10. @RequestMapping("/customers")
  11. public class CustomerController {
  12. @Autowired
  13. private CustomerService service;
  14. public void setService(CustomerService service) {
  15. this.service = service;
  16. }
  17. @RequestMapping("/list")
  18. @ResponseBody
  19. public List<Customer> list(){
  20. return service.list();
  21. }
  22. @RequestMapping("/update")
  23. @ResponseBody
  24. public String update() {
  25. Customer customers1 = new Customer();
  26. customers1.setCustId(1013);
  27. customers1.setCustName("lffxxx");
  28. customers1.setCustState("ss");
  29. customers1.setCustCity("BJ");
  30. customers1.setCustState("CN");
  31. customers1.setCustZip("10001");
  32. return service.update(customers1) ? "success":"error";
  33. }
  34. }

Maven依赖配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.ff</groupId>
  7. <artifactId>Demo5</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <!--打包方式默认是jar,web工程打包为warJava工程打包为jar -->
  10. <packaging>war</packaging>
  11. <!--属性信息比如字符编码等 -->
  12. <properties>
  13. <!--字符编码 -->
  14. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15. <!--Maven项目的JDK版本 -->
  16. <maven.compiler.source>8</maven.compiler.source>
  17. <maven.compiler.target>8</maven.compiler.target>
  18. </properties>
  19. <!-- 依赖-->
  20. <dependencies>
  21. <!-- JavaEE基本依赖-->
  22. <dependency>
  23. <groupId>javax.servlet</groupId>
  24. <artifactId>javax.servlet-api</artifactId>
  25. <version>4.0.1</version>
  26. <scope>provided</scope>
  27. </dependency>
  28. <dependency>
  29. <groupId>javax.servlet</groupId>
  30. <artifactId>jsp-api</artifactId>
  31. <version>2.0</version>
  32. <scope>provided</scope>
  33. </dependency>
  34. <!-- SpringMVC -->
  35. <dependency>
  36. <groupId>org.springframework</groupId>
  37. <artifactId>spring-webmvc</artifactId>
  38. <version>5.2.8.RELEASE</version>
  39. </dependency>
  40. <!-- 面向切面编程-->
  41. <dependency>
  42. <groupId>org.aspectj</groupId>
  43. <artifactId>aspectjweaver</artifactId>
  44. <version>1.9.6</version>
  45. </dependency>
  46. <dependency>
  47. <groupId>org.aspectj</groupId>
  48. <artifactId>aspectjrt</artifactId>
  49. <version>1.9.6</version>
  50. </dependency>
  51. <!-- mybatis相关包-->
  52. <dependency>
  53. <groupId>org.mybatis</groupId>
  54. <artifactId>mybatis</artifactId>
  55. <version>3.5.5</version>
  56. </dependency>
  57. <dependency>
  58. <groupId>org.mybatis</groupId>
  59. <artifactId>mybatis-spring</artifactId>
  60. <version>2.0.5</version>
  61. </dependency>
  62. <dependency>
  63. <groupId>org.springframework</groupId>
  64. <artifactId>spring-jdbc</artifactId>
  65. <version>5.2.8.RELEASE</version>
  66. </dependency>
  67. <!-- 数据库-->
  68. <dependency>
  69. <groupId>mysql</groupId>
  70. <artifactId>mysql-connector-java</artifactId>
  71. <version>5.1.49</version>
  72. </dependency>
  73. <!-- 数据库连接池-->
  74. <dependency>
  75. <groupId>com.alibaba</groupId>
  76. <artifactId>druid</artifactId>
  77. <version>1.1.22</version>
  78. </dependency>
  79. <!-- 日志 -->
  80. <dependency>
  81. <groupId>ch.qos.logback</groupId>
  82. <artifactId>logback-classic</artifactId>
  83. <version>1.2.3</version>
  84. </dependency>
  85. <!-- 单元测试 -->
  86. <dependency>
  87. <groupId>junit</groupId>
  88. <artifactId>junit</artifactId>
  89. <version>4.13</version>
  90. <scope>test</scope>
  91. </dependency>
  92. <!-- domain模型转JSON字符串 -->
  93. <dependency>
  94. <groupId>com.fasterxml.jackson.core</groupId>
  95. <artifactId>jackson-databind</artifactId>
  96. <version>2.11.0</version>
  97. </dependency>
  98. <!-- 解析Multipart类型参数 -->
  99. <dependency>
  100. <groupId>commons-fileupload</groupId>
  101. <artifactId>commons-fileupload</artifactId>
  102. <version>1.4</version>
  103. </dependency>
  104. </dependencies>
  105. </project>

设置打包资源

  1. <!--构建信息比如插件配置等-->
  2. <build>
  3. <finalName>demo5</finalName>
  4. <!-- 说明资源的位置(哪些东西算是资源) -->
  5. <resources>
  6. <!-- resources文件里面的内容要进行打包 -->
  7. <resource>
  8. <directory>src/main/resources</directory>
  9. </resource>
  10. <!-- java文件里面的内容要进行打包 -->
  11. <resource>
  12. <directory>src/main/java</directory>
  13. <includes>
  14. <include>**/*.properties</include>
  15. <include>**/*.xml</include>
  16. </includes>
  17. </resource>
  18. </resources>
  19. </build>

父子容器

Spring、SpringMVC和Mybatis整合 - 图1

父容器和子容器相互隔离,可以存在相同名称的Bean。子容器可以访问父容器里面的Bean,父容器不能访问子容器的Bean,也就是控制器层可以注入Service的代码,Service不能注入Controller层的代码。当在子容器中查找Bean时,比如调用getBean方法会先在子容器里面查找,如果没有就会向父容器里面查找,直到查找到为止。

配置父子容器文件

新建子容器配置文件dispatcherServlet.xml(名字可以随意起,建议叫这个)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
  7. <context:component-scan base-package="com.lff.controller"/>
  8. <mvc:annotation-driven />
  9. </beans>

注意此时扫描的包,确保只扫描SpringMVC的Bean,如Controller等

  1. <context:component-scan base-package="com.lff.controller"/>

父容器配置文件还是applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
  7. <context:component-scan base-package="com.lff.service"/>
  8. <!-- 数据源(Druid) 当然可以使用其的数据源-->
  9. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
  10. <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  11. <property name="url" value="jdbc:mysql://localhost:3306/customer_test"/>
  12. <property name="username" value="root"/>
  13. <property name="password" value="root"/>
  14. </bean>
  15. <!-- 创建SqlSessionFactory -->
  16. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  17. <!-- 数据源 -->
  18. <property name="dataSource" ref="dataSource"/>
  19. <!-- 这个包底下的类会自动设置别名(一般是领域模型) -->
  20. <property name="typeAliasesPackage" value="com.lff.domain"/>
  21. <!-- 映射文件的位置 -->
  22. <!-- <property name="mapperLocations">-->
  23. <!-- <array>-->
  24. <!-- <value>classpath:mappers/*.xml</value>-->
  25. <!-- </array>-->
  26. <!-- </property>-->
  27. </bean>
  28. <!-- 扫描dao,生成Dao的代理对象 -->
  29. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  30. <!-- 设置SqlSessionFactoryBean的id -->
  31. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
  32. <!-- 设置dao的包 -->
  33. <property name="basePackage" value="com.lff.dao"/>
  34. </bean>
  35. <!-- 事务管理器 -->
  36. <bean id="transactionManager"
  37. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  38. <!-- 数据源 -->
  39. <property name="dataSource" ref="dataSource" />
  40. </bean>
  41. <!-- 附加代码:事务管理代码 -->
  42. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  43. <tx:attributes>
  44. <tx:method name="*"/>
  45. <tx:method name="list*" read-only="true"/>
  46. <tx:method name="get*" read-only="true"/>
  47. </tx:attributes>
  48. </tx:advice>
  49. <!-- 切面 -->
  50. <aop:config>
  51. <aop:pointcut id="pc" expression="within(com.mj.service..*)"/>
  52. <aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/>
  53. </aop:config>
  54. </beans>

注意父容器扫描的是Service层,千万不要扫描Controller层,一般扫描非SpringMVC共用的Bean

  1. <context:component-scan base-package="com.lff.service"/>

上面的MyBatis配置文件中,我们并没有告诉Mapper文件的位置

  1. <!-- 创建SqlSessionFactory -->
  2. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  3. <!-- 数据源 -->
  4. <property name="dataSource" ref="dataSource"/>
  5. <!-- 这个包底下的类会自动设置别名(一般是领域模型) -->
  6. <property name="typeAliasesPackage" value="com.lff.domain"/>
  7. <!-- 映射文件的位置 -->
  8. <!-- <property name="mapperLocations">-->
  9. <!-- <array>-->
  10. <!-- <value>classpath:mappers/*.xml</value>-->
  11. <!-- </array>-->
  12. <!-- </property>-->
  13. </bean>

因为我们可以把mapper文件放在和Dao相同的目录下,并且文件名称与Dao的类名保持一致。
image.png

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.lff.dao.CustomerDao">
  6. <!--查询所有的顾客-->
  7. <select id="list" resultMap="customerDomain">
  8. SELECT * FROM Customers
  9. </select>
  10. <resultMap id="customerDomain" type="com.lff.domain.Customer">
  11. <result property="custName" column="cust_name" />
  12. <result property="custCity" column="cust_city" />
  13. </resultMap>
  14. <!-- 移除一个顾客-->
  15. <delete id="remove" parameterType="int">
  16. DELETE FROM Customers WHERE cust_id = #{id}
  17. </delete>
  18. <update id="update" parameterType="com.lff.domain.Customer">
  19. UPDATE Customers SET cust_name=#{custName},cust_address = #{custAddress},cust_city=#{custCity},cust_state=#{custState},cust_zip=#{custZip} where cust_id = #{custId}
  20. </update>
  21. <insert id="save" parameterType="com.lff.domain.Customer">
  22. INSERT INTO Customers(cust_id,cust_name,cust_address,cust_city,cust_state,cust_zip) values (#{custId},#{custName},#{custAddress},#{custCity},#{custState},#{custZip})
  23. </insert>
  24. </mapper>

当然还需要在Maven配置文件中加如下配置,因为Maven默认情况下是不会对我们的源代码文件里面的XML、Properties文件进行打包的

  1. <!--构建信息比如插件配置等-->
  2. <build>
  3. <finalName>demo5</finalName>
  4. <!-- 说明资源的位置(哪些东西算是资源) -->
  5. <resources>
  6. <!-- resources文件里面的内容要进行打包 -->
  7. <resource>
  8. <directory>src/main/resources</directory>
  9. </resource>
  10. <!-- java文件里面的内容要进行打包 -->
  11. <resource>
  12. <directory>src/main/java</directory>
  13. <includes>
  14. <include>**/*.properties</include>
  15. <include>**/*.xml</include>
  16. </includes>
  17. </resource>
  18. </resources>
  19. </build>

这样才会把Mapper文件也打包进行去
image.png

加载父容器、子容器

在web.xml文件中进行加载父容器、子容器

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  5. version="4.0">
  6. <!-- 使用SpringMVC提供的DispatcherServlet进行处理拦截客户端的请求-->
  7. <servlet>
  8. <servlet-name>springmvc</servlet-name>
  9. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10. <!-- 加载Spring的配置文件,配置文件里面配置要扫描的类等-->
  11. <init-param>
  12. <param-name>contextConfigLocation</param-name>
  13. <!-- 加载子容器-->
  14. <param-value>classpath:dispatcherServlet.xml</param-value>
  15. </init-param>
  16. <!-- 项目部署到服务器,就会创建Servlet -->
  17. <load-on-startup>0</load-on-startup>
  18. </servlet>
  19. <servlet-mapping>
  20. <servlet-name>springmvc</servlet-name>
  21. <!-- 拦截客户端所有请求路径-->
  22. <url-pattern>/</url-pattern>
  23. </servlet-mapping>
  24. <!-- 父容器的配置-->
  25. <context-param>
  26. <param-name>contextConfigLocation</param-name>
  27. <param-value>classpath:applicationContext.xml</param-value>
  28. </context-param>
  29. <!-- 监听器监听到项目的部署就会加载上面的context-param,加载父容器applicationContext.xml-->
  30. <listener>
  31. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  32. </listener>
  33. <!-- 使用springMVC自带的过滤器处理post请求乱码问题-->
  34. <filter>
  35. <filter-name>characterEncodingFilter</filter-name>
  36. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  37. <init-param>
  38. <param-name>encoding</param-name>
  39. <param-value>UTF-8</param-value>
  40. </init-param>
  41. </filter>
  42. <filter-mapping>
  43. <filter-name>characterEncodingFilter</filter-name>
  44. <url-pattern>/*</url-pattern>
  45. </filter-mapping>
  46. </web-app>

这样在请求控制器层就可以了。

纯注解的方式实现SSM整合

做好上面准备和依赖后(Dao层、Service层、Controller层、Maven依赖)的处理步骤如下

web.xml的配置可以删除

当项目启动后会加载web.xml文件,我们可以使用如下方式替代

  1. package com.lff.config;
  2. import org.springframework.web.filter.CharacterEncodingFilter;
  3. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
  4. import javax.servlet.FilterRegistration;
  5. import javax.servlet.ServletContext;
  6. import javax.servlet.ServletException;
  7. public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
  8. /**
  9. * 父容器的配置类
  10. */
  11. @Override
  12. protected Class<?>[] getRootConfigClasses() {
  13. return new Class[]{SpringConfig.class};
  14. }
  15. /**
  16. * 子容器的配置类(SpringMVC相关的配置类)
  17. */
  18. @Override
  19. protected Class<?>[] getServletConfigClasses() {
  20. return new Class[]{SpringMVCConfig.class};
  21. }
  22. /**
  23. * 配置DispatcherServlet的url-pattern
  24. */
  25. @Override
  26. protected String[] getServletMappings() {
  27. return new String[]{"/"};
  28. }
  29. @Override
  30. public void onStartup(ServletContext servletContext) throws ServletException {
  31. super.onStartup(servletContext);
  32. // 添加Filter
  33. FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("CharacterEncodingFilter", new CharacterEncodingFilter("UTF-8"));
  34. encodingFilter.addMappingForUrlPatterns(null, false, "/*");
  35. }
  36. }

项目部署的时候,就会先看有没有实现WebApplicationInitializer接口,如果实现这个接口就会实例化实现该接口的类,创建该类的对象,调用onStartup方法。而上面AbstractAnnotationConfigDispatcherServletInitializer类的父类实现了WebApplicationInitializer接口

  1. public interface WebApplicationInitializer {
  2. void onStartup(ServletContext var1) throws ServletException;
  3. }

有些项目也使用如下方式设置,直接实现WebApplicationInitializer接口

  1. @Override
  2. public void onStartup(ServletContext servletContext) throws ServletException {
  3. // 父容器配置
  4. AnnotationConfigWebApplicationContext springCtx = new AnnotationConfigWebApplicationContext();
  5. springCtx.register(SpringConfig.class);
  6. // 通过监听器加载配置信息
  7. servletContext.addListener(new ContextLoaderListener(springCtx));
  8. // 子容器配置
  9. AnnotationConfigWebApplicationContext mvcCtx = new AnnotationConfigWebApplicationContext();
  10. mvcCtx.register(SpringMVCConfig.class);
  11. ServletRegistration.Dynamic servlet = servletContext.addServlet(
  12. "DispatcherServlet",
  13. new DispatcherServlet(mvcCtx));
  14. servlet.setLoadOnStartup(0);
  15. servlet.addMapping("/");
  16. // filter
  17. FilterRegistration.Dynamic encodingFilter = servletContext.addFilter(
  18. "CharacterEncodingFilter",
  19. new CharacterEncodingFilter("UTF-8"));
  20. encodingFilter.addMappingForUrlPatterns(null, false, "/*");
  21. }

没有必要使用这种方式,不够清晰直观,并且不好记忆。

父容器的配置

  1. package com.lff.config;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import org.mybatis.spring.SqlSessionFactoryBean;
  4. import org.mybatis.spring.annotation.MapperScan;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.ComponentScan;
  8. import org.springframework.context.annotation.PropertySource;
  9. import org.springframework.core.io.ClassPathResource;
  10. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  11. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  12. import org.springframework.transaction.annotation.EnableTransactionManagement;
  13. import javax.sql.DataSource;
  14. @ComponentScan({"com.lff.service","com.lff.converter"})
  15. @MapperScan("com.lff.dao")
  16. @EnableTransactionManagement
  17. public class SpringConfig {
  18. //配置数据源
  19. @Bean
  20. public DataSource dataSource() {
  21. DruidDataSource ds = new DruidDataSource();
  22. ds.setDriverClassName("com.mysql.jdbc.Driver");
  23. ds.setUrl("jdbc:mysql://localhost:3306/customer_test");
  24. ds.setUsername("root");
  25. ds.setPassword("root");
  26. return ds;
  27. }
  28. //配置核心Mybatis核心工厂
  29. @Bean
  30. public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception {
  31. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  32. bean.setDataSource(dataSource);
  33. bean.setTypeAliasesPackage("com.lff.domain");//设置实体类别名
  34. PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
  35. // bean.setMapperLocations(resolver.getResources("classpath:/mappers/*.xml"));//配置Mapper映射文件的路径
  36. // 如果有mybatis-config配置文件可以在这里设置,指定配置文件的位置
  37. // bean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
  38. return bean;
  39. }
  40. //配置事务管理器,替换配置里面的DataSourceTransactionManager
  41. @Bean
  42. public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){
  43. DataSourceTransactionManager dm = new DataSourceTransactionManager();
  44. dm.setDataSource(dataSource);
  45. return dm;
  46. }
  47. }

子容器的配置

  1. package com.lff.config;
  2. import com.lff.converter.DateConverter;
  3. import com.lff.interceptor.MyInterceptor;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.ComponentScan;
  7. import org.springframework.format.FormatterRegistry;
  8. import org.springframework.http.converter.HttpMessageConverter;
  9. import org.springframework.http.converter.StringHttpMessageConverter;
  10. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
  11. import org.springframework.web.multipart.commons.CommonsMultipartResolver;
  12. import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
  13. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  14. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  15. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  16. import org.springframework.web.servlet.view.InternalResourceViewResolver;
  17. import java.nio.charset.StandardCharsets;
  18. import java.util.List;
  19. //思路:如果想配置一个东西又不知道怎么配置可以查看该类的父类都可以配置哪些东西
  20. @ComponentScan({"com.lff.controller", "com.lff.interceptor"})
  21. @EnableWebMvc //一定要加这个注解,不要问为什么,否则不好使
  22. public class SpringMVCConfig implements WebMvcConfigurer {
  23. @Autowired
  24. private MyInterceptor myInterceptor;
  25. @Autowired
  26. private DateConverter dateConverter;
  27. // 可以在这里设置路径前缀、后缀
  28. @Bean
  29. public InternalResourceViewResolver viewResolver() {
  30. InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  31. resolver.setPrefix("/WEB-INF/page/");
  32. resolver.setSuffix(".jsp");
  33. return resolver;
  34. }
  35. // 文件上传配置
  36. @Bean
  37. public CommonsMultipartResolver multipartResolver() {
  38. CommonsMultipartResolver resolver = new CommonsMultipartResolver();
  39. resolver.setDefaultEncoding("UTF-8");
  40. return resolver;
  41. }
  42. // 如果需要拦截器,在这里添加拦截器配置
  43. @Override
  44. public void addInterceptors(InterceptorRegistry registry) {
  45. registry.addInterceptor(myInterceptor)
  46. .addPathPatterns("/**")
  47. .excludePathPatterns("/asset/**");
  48. }
  49. // 如果需要转换器,在这里配置,比如日期格式转换等
  50. @Override
  51. public void addFormatters(FormatterRegistry registry) {
  52. registry.addConverter(dateConverter);
  53. }
  54. /**
  55. * 相当于<mvc:default-servlet-handler/>
  56. * 用以处理静态资源
  57. */
  58. @Override
  59. public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  60. configurer.enable();
  61. }
  62. // 用于处理字符编码乱码问题
  63. @Override
  64. public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  65. // 设置返回的普通字符串的编码
  66. StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
  67. stringConverter.setDefaultCharset(StandardCharsets.UTF_8);
  68. converters.add(stringConverter);
  69. // 设置返回的JSON数据的编码
  70. MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
  71. jsonConverter.setDefaultCharset(StandardCharsets.UTF_8);
  72. converters.add(jsonConverter);
  73. }
  74. }

上面如果不使用拦截器和转换器可以去掉,根据情况在配置文件里面添加内容。
当配置一项的时候,要想清楚是属于Service层的东西还是属于Controller层的东西,Service层的东西就在父容器里面配置,Controller层的东西就在子容器里面配置,如果都需要就配置在父容器里面。