MuLeI
做创造价值的人
MuLeI的小站

SSM整合配置

SSM整合配置

SSM整合配置

  • 通过Spring IOC容器管理第三方框架对象,让多框架形成整体

  • Spring MVC 提供控制器,基于Spring的web交互能力,作为开发web应用的基础

  • Spring 处于最底层,对应用程序对象进行创建和管理。其它所有“框架”的对象都通过Spring进行统筹协调

  • MyBatis 与底层数据库进行增删改查的操作

一、Spring与Spring MVC环境配置

1. 引入spring-webmvc依赖

pom.xml

<repositories>
    <repository>
        <id>aliyun</id>
        <name>aliyun</name>
        <url>https://maven.aliyun.com/repository/public</url>
    </repository>
</repositories>

<dependencies>
    <!--
        1.配置相应依赖,分别是spring-webmvc,freemarker,spring-context-support,
        jackson-core,jackson-annotations,jackson-databind
    -->
    <!-- Spring MVC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>
    <!-- Freemarker -->
    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.30</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>
    <!-- Jackson -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.12.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.12.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.12.3</version>
    </dependency>
</dependencies>

2. 配置DispatcherServlet

web.xml

<web-app ... >
    <!-- 2.配置DispacherServlet -->
    <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:applicationContext*.xml</param-value>
        </init-param>
        <!-- 启动时初始化DispatcherServlet -->
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3. 启用Spring MVC注解模式

applicationContext.xml

<beans ... >
    <!-- 3.启用Spring MVC注解模式 -->
    <!-- Spring框架启用注解模式,容器初始化时实例化Controller/Service等对象 -->
    <context:component-scan base-package="..."/>
    <!-- 开启SpringMVC注解模式 -->
    <mvc:annotation-driven/>
    <!-- 排除js/css等静态资源 -->
    <mvc:default-servlet-handler/>
</beans>

4. 配置请求与响应字符集,JSON序列化组件

请求中的中文乱码 -> web.xml

<web-app ... >
    <!-- 4.配置请求与响应字符集 -->
    <!-- 解决POST请求中文乱码,这里的配置仅对POST请求生效,Tomcat8以后的版本默认支持“UTF-8”的GET请求编码 -->
    <filter>
        <filter-name>characterFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

响应中的中文乱码,JSON序列化组件 -> applicationContext.xml

<beans ... >
    <mvc:annotation-driven>
        <!-- 解决响应输出产生的中文乱码 -->
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <!-- 直接向客户端输出时采用UTF-8编码 -->
                        <value>text/html;charset=utf-8</value>
                        <!-- 配置Json序列化组件 -->
                        <!-- JSON(Jackson)序列化输出时采用UTF-8编码 -->
                        <value>application/json;charset=utf-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>

5. 配置FreeMaker模板引擎

applicationContext.xml

<beans ... >
    <!-- 5.配置Freemarker模板引擎 -->
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <!-- FreeMarker脚本存放位置 -->
        <property name="templateLoaderPath" value="/WEB-INF/ftl"/>
        <property name="freemarkerSettings">
            <props>
                <!-- 读取ftl文件时采用UTF-8编码(脚本内部) -->
                <prop key="defaultEncoding">UTF-8</prop>
            </props>
        </property>
    </bean>
    <bean id="ViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <!-- Freemarker模板引擎产生html片段返回数据时采用UTF-8编码 -->
        <property name="contentType" value="text/html;charset=utf-8"/>
        <property name="suffix" value=".ftl"/>
    </bean>
</beans>

二、Spring与Mybatis的整合配置

1. 引入mybatis-spring依赖及驱动

pom.xml

<dependencies>
    <!-- 1.引入依赖 -->
    <!-- spring-jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>
    <!-- Mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.4</version>
    </dependency>
    <!-- Mybatis与Spring整合组件 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.3</version>
    </dependency>
    <!-- jdbc驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.19</version>
    </dependency>
    <!-- 连接池 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.14</version>
    </dependency>
</dependencies>

2. 配置数据源与连接池

applicationContext.xml

<beans ... >
    <!-- 2.配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/databasename?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"/>
        <property name="username" value="root"/>
        <property name="password" value="password"/>
        <property name="initialSize" value="5"/>
        <property name="maxActive" value="20"/>
    </bean>
</beans>

3. 配置SqlSessionFactory

applicationContext.xml

<beans ... >
    <!-- 3.SqlSessionFactoryBean用于根据配置信息创建SqlSessionFactory,不再需要自己编码创建 -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mappers/*.xml"/>
        <!-- 指定Mybatis配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
</beans>

4. 配置Mapper扫描器

applicationContext.xml

<beans ... >
    <!-- 4.配置Mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="...mapper"/>
    </bean>
</beans>

5. 创建配置文件mybatis-config.xml

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 驼峰命名转换 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

三、整合其他组件:声明式事务、日志、任务调度 …

1. 配置logback日志输出

pom.xml

<dependencies>
    <!-- logback日志组件 -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency>
</dependencies>

设置日志输出样式 -> logback.xml

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <!-- 直接向控制台输出 -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{HH:mm:ss} %-5level [%thread] %logger{30} - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>
    <root level="debug">
        <appender-ref ref="console"/>
    </root>
</configuration>

2. 声明式事务配置

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mv="http://www.springframework.org/schema/mvc"
       xmlns:task="http://www.springframework.org/schema/task"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/task
            http://www.springframework.org/schema/task/spring-task.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/tx
            https://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 声明式事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

常用注解

@Transactional
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)

3. 整合JUnit单元测试

pom.xml

<dependencies>
    <!-- 单元测试依赖 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope><!--不打包-->
    </dependency>
</dependencies>

测试用例需要依托于Spring IOC测试用例运行,需要添加注解:

@RunWith(SpringJUnit4ClassRunner.class)//将JUnit控制权交给Spring,并通过IOC自动初始化
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})//Spring IOC容器根据配置文件中的规定完成初始化工作
本博客所有文章除特别声明外,均采用CC BY-SA 4.0 协议,转载请注明出处!

发表回复

textsms
account_circle
email

MuLeI的小站

SSM整合配置
一、Spring与Spring MVC环境配置 二、Spring与Mybatis的整合配置 三、整合其他组件
扫描二维码继续阅读
2021-07-06