看过之前的蜕变系列文章,相信你对SpringMVC 、Spring、 Mybatis有了一些应用上的感性认识。但是都还是单个使用,并没有放到一起来使用,今天我们讲讲怎样将这三个框架结合起来使用,学会搭建属于自己的开发框架——也就是俗称的SSM框架。
每月底工厂君会根据后台记录筛选转发文章到朋友圈的前三位的朋友,给与奖励,第一名100元,第二名50元,第三名30元的现金奖励。
猿蜕变同样是一个原创系列文章,帮助你从一个普通的小白,开始掌握一些行业内通用的框架技术知识以及锻炼你对系统设计能力的提升,完成属于你的蜕变,更多精彩内容,敬请大家关注公主号猿人工厂,点击猿人养成获取!
到目前为止,我们已经学习过三个框架了,SpringMVC Spring Mybatis. Spring MVC 专注于MVC方面的事情,Spring作为IOC容器管理Bean的生命周期,MyBatis用于专注于数据持久层面的事情。三个框架分别负责处理三方面的问题,有条不紊,各有分工。今天我们就来将三个框架融合到一起,让他们协同工作,发挥各自的优势。这也是以后大家会在工作中经常使用的框架——SSM(Spring MVC Spring Mybatis的缩写),不过嘛SpringMVC属于Spring的一部分,你叫SM也不是不可以哒。Spring MVC本来就是Spring生态圈的一部分,这两者间天生就是融合的,不存在整合一说,我们主要做的事情,是将Mybatis和Spring融合到一起,就好了——将SqlSessionFactory和事务处理方面的事情交给Spring来管理。
如果你学到今天都还不会创建web应用?你真滴可能不太适合做一只猿类,放弃吧。
增加项目依赖
修改pom.xml增加SpringMVC Spring Mybatis相关项目依赖
<?xml version="1.0"encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pz.study.frame</groupId>
<artifactId>ssmDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>mybatis Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- 本文主要是以测试用例的方式来使用 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- springMVC相关start -->
<!--servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.8</version>
</dependency>
<!-- 支持日期注解 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9</version>
</dependency>
<!-- hibernate-validator用于数据校验 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<artifactId>commons-fileupload</artifactId>
<groupId>commons-fileupload</groupId>
<version>1.3.3</version>
</dependency>
<!-- springMVC相关end -->
<!-- Spring相关Start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- 使用AOP加入aspectj依赖 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<!-- 使用AOP加入Spring对AOP的aspectj的支持依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
<!-- Spring相关end -->
<!-- 加入mybatis<dependency> <groupId>org.mybatis</groupId><artifactId>mybatis</artifactId>
<version>3.2.7</version></dependency> -->
<!-- 数据库相关 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!--druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!-- 方便查看最终输出的sql -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
<build>
<finalName>ssmDemo</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<pluginManagement><!-- lockdown plugins versions to avoid using Maven
defaults (may bemoved to parent pom) -->
<plugins>
<!--maven插件 -->
<!--jdk编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<!--tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<!-- tomcat7的插件, 不同tomcat版本这个也不一样 -->
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<!-- 通过maven tomcat7:run运行项目时,访问项目的端口号 -->
<port>80</port>
<!-- 项目访问路径 本例:localhost:9090, 如果配置的aa, 则访问路径为localhost:9090/aa -->
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
分类建立配置文件目录
在resources文件目录下建立两个子目录spring和mapper用于存放spring的各个模块配置以及mybatis的mapper文件。这一步你也可以省略,只是以后配置文件显得比较杂乱。建立项目总控文件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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
default-autowire="byName">
<!-- 注册组件扫描器 -->
<context:component-scan base-package="com.pz.web.study.ssm.*">
</context:component-scan>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders"value="true" />
<property name="locations">
<list>
<value>classpath:db.properties</value>
</list>
</property>
</bean>
<import resource="spring/spring-mybatis.xml"/>
<import resource="spring/spring-service.xml"/>
<import resource="spring/spring-tx.xml"/>
<import resource="spring/spring-mvc.xml"/>
</beans>
指定配置web.xml
<?xml version="1.0"encoding="UTF-8"?>
<web-app version="2.4"xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>order-center</display-name>
<!-- 配置字符编码处理Filter-->
<filter>
<filter-name>EncodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置SpringMVC前端控制器 -->
<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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
配置mybatis总控文件
<?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>
<typeAliases>
<typeAlias type="com.pz.web.study.ssm.domain.TravelRoute"alias="TravelRoute" />
</typeAliases>
<mappers>
<!--注册映射文件 -->
<mapper resource="mapper/TravelRouteMapper.xml"/>
</mappers>
</configuration>
配置spring整合mybatis的文件
spring-mybatis.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: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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
default-autowire="byName">
<!-- 数据库连接池 -->
<bean id="dataSource"class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url"value="${jdbc.url}" />
<property name="username"value="${jdbc.username}" />
<property name="password"value="${jdbc.password}" />
<property name="driverClassName"value="com.mysql.jdbc.Driver" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize"value="5" />
<property name="minIdle"value="5" />
<property name="maxActive"value="20" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait"value="3000" />
<property name="useUnfairLock"value="true" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis"value="5000" />
<!--最小空闲时间 jed同事建议30s -->
<property name="minEvictableIdleTimeMillis"value="30000" />
<property name="validationQuery"value="SELECT 1" />
<property name="testWhileIdle"value="true" />
<property name="testOnBorrow"value="false" />
<property name="testOnReturn"value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements"value="false" />
<property name="maxPoolPreparedStatementPerConnectionSize"
value="0"/>
</bean>
<!-- 让spring管理sqlsessionfactory使用mybatis和spring整合包中的 -->
<bean id="mybatiSqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource"ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation"value="classpath:mybatis.xml" />
</bean>
<!-- 自动扫描 将Mapper接口生成代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName"value="mybatiSqlSessionFactory"/>
<property name="basePackage"value="com.pz.web.study.ssm.dao" />
</bean>
</beans>
配置spring-mvc相关文件
spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd
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"
default-autowire="byName">
<!-- 自动扫描com.pz.web.study.springmvc.controller路径下的所有文件,并根据注解完成注入的工作 -->
<context:component-scan base-package="com.pz.web.study.ssm。controller"></context:component-scan>
<!-- 视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"value="/WEB-INF/jsp/" />
<property name="suffix"value=".jsp" />
</bean>
<!--配置类型转换器 -->
<bean id="dateConverter"class="com.pz.web.study.ssm.util.SimpleDateConverter"/>
<!--配置类型转换服务bean-->
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters"ref="dateConverter" />
</bean>
<!--验证器 -->
<bean id="hibernateValidator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass"value="org.hibernate.validator.HibernateValidator"/>
</bean>
<!-- 让Spring启用对annotation的支持 -->
<mvc:annotation-driven conversion-service="conversionService"
validator="hibernateValidator">
<mvc:message-converters register-defaults="true">
<bean
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json</value>
<value>application/xml;charset=UTF-8</value>
</list>
</property>
<property name="features">
<list>
<!-- 默认的意思就是不配置这个属性,配置了就不是默认了 -->
<!-- 是否输出值为null的字段 ,默认是false -->
<value>WriteMapNullValue</value>
<value>WriteNullNumberAsZero</value>
<value>WriteNullListAsEmpty</value>
<value>WriteNullStringAsEmpty</value>
<value>WriteNullBooleanAsFalse</value>
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="com.pz.web.study.ssm.util.MyHandleExceptionResolver"/>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置字符编码防止文件名乱码 -->
<property name="defaultEncoding"value="utf-8" />
<!--设置上传文件的总大小,单位是字节b -->
<property name="maxUploadSize"value="2048576" />
<!--设置内存缓冲区的大小,当超过该值的时候会写入到临时目录 -->
<property name="maxInMemorySize"value="2048576" />
<!--设置临时目录 -->
<property name="uploadTempDir"value="temp" />
<!--是否使用懒加载,默认是false -->
<property name="resolveLazily"value="true" />
</bean>
<mvc:default-servlet-handler />
</beans>
配置service层相关文件
spring-service.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd
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"
default-autowire="byName">
<bean id="travelRouteService"class="com.pz.web.study.ssm.service.impl.TravelRouteServiceImpl"/>
</beans>
配置事务管理相关文件
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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
default-autowire="byName">
<!-- 事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource"ref="dataSource" />
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice"transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*"propagation="REQUIRED" />
<tx:method name="insert*"propagation="REQUIRED" />
<tx:method name="add*"propagation="REQUIRED" />
<tx:method name="create*"propagation="REQUIRED" />
<tx:method name="delete*"propagation="REQUIRED" />
<tx:method name="update*"propagation="REQUIRED" />
<tx:method name="find*"propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*"propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*"propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<!--切入点必须是在service层-->
<aop:advisor advice-ref="txAdvice"
pointcut="execution(*com.pz.web.study.ssm.service.*.*(..))" />
</aop:config>
</beans>
配置数据库
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/route?characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
配置log4j
log4j.properties
log4j.rootLogger=trace,console
log4j.appender.console= org.apache.log4j.ConsoleAppender
log4j.appender.console.Target= System.out
log4j.appender.console.layout= org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%-5p][%d{yyyy-MM-ddHH:mm:ss}]%m%n
我建了一个技术群,群里有很多高手,加小编微信,备注:学习。带你见识更多的高手,帮你快速成长。