进行SSM框架整合时,3个框架的分工如下所示。
• MyBatis 负责与数据库进行交互。
• Spring 负责事务管理,Spring可以管理持久层的Mapper对象及业务层的Service对象。由于Mapper对象和Service对象都在Spring容器中,所以可以在业务逻辑层通过Service对象调用持久层的Mapper对象。
• Spring MVC 负责管理表现层的Handler(controller)。Spring MVC容器是Spring容器的子容器,因此Spring MVC容器可以调用Spring容器中的Service对象
对于初学者来说:最大的问题便是“配置地狱了”,
因此这篇文章就直接列出SSM整合的配置类,关键配置在代码中都有解释。此文章在之后的学习也可带来一定的方便
同样作为初学者的我来说,配置类中可能有瑕疵或者理解不对的地方,还望诸君海涵并指出。
废话少说,直接上代码:
pom.xml
<?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.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wsx.ssm</groupId>
<artifactId>learing</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!--整合Mybatis相关的-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--整合SpringMVC相关的-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--事务aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!--Servlet相关的 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--其他依赖:根据实际需求选配 -->
<!--lombok:简化实体类编写-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<!--
资源插件: 处理src/main/java目录(即mapper)和src/main/resources中的xml文件
不然IDEA无法将xml编译(注,IDEA需要配置,eclipse不用)
-->
<resources>
<resource>
<directory>src/main/java</directory> <!--所在的目录-->
<includes> <!--包括目录下的 .properties和 .xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory> <!--同理-->
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
spring-dao.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: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/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--
@整合mybatis
该配置文件是由 applicationContext.xml 引入,再交给Spring管理
核心功能都可有它完成,因此若无辅助功能可完全代替mybatis-config.xml
-->
<!-- 1.关联数据源文件 -->
<context:property-placeholder location="classpath:database.properties"/>
<!--
2.数据库连接池
dbcp 半自动化操作 不能自动连接
c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面):class="com.mchange.v2.c3p0.ComboPooledDataSource"
druid 自动化操作(并且有日志监控功能):class="com.alibaba.druid.pool.DruidDataSource"
细节点:因为 dataSource 需要注入到sqlSessionFactory中,所以用id="dataSource"标识
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置连接池属性 -->
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- c3p0连接池的私有属性 -->
<property name="initialPoolSize" value="5"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--
3.配置SqlSessionFactory对象,交给SpringIOC
(对比学习MyBatis Test类中那几个步骤需要的东西来理解)
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池:dataSource -->
<property name="dataSource" ref="dataSource"/>
<!-- 指定mapper接口位置(用于mapper和接口不在统一文件夹下的情况)-->
<!-- <property name="mapperLocations" value="classpath:mapper/*.xml"></property>-->
<!-- 配置(绑定)MyBaties全局配置文件:mybatis-config.xml(里面指定了mapper文件的位置) -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 设置实体类别名属于辅助配置,也可在mybatis-config.xml配置 -->
<!-- <property name="typeAliasesPackage" value="com.wsx.pojo"></property>-->
</bean>
<!--
上面配置SqlSessionFactory,并指定了mapper文件的位置,接下来还需指明接口
4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 (动态代理方式)
-->
<!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory (上面已经配了这步应该可以省略)-->
<!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>-->
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.wsx.dao"/>
</bean>
</beans>
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">
<!--核心配置内容在spring-dao.xml已完成,该配置类在spring-dao.xml中绑定。这个配置类可选择配置一些辅助信息-->
<configuration>
<!--原来配置数据源,现在交给Spring去做 -->
<!--设置日志 LOG4J-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--设置实体类别名-->
<typeAliases>
<package name="com.wsx.pojo"/>
</typeAliases>
<!--指定其他mapper文件的位置:
其他其他mapper文件目的是找到其他文件的sql语句
mapper和接口名字一样用class属性就行,不一样就用resource属性
-->
<mappers>
<mapper class="com.wsx.dao.StudentMapper"/>
</mappers>
</configuration>
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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--
@整合SpringMVC
该配置文件是由 applicationContext.xml 引入,再交给Spring管理
-->
<!-- 1.开启SpringMVC注解驱动 -->
<mvc:annotation-driven />
<!-- 2.静态资源默认servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 显示ViewResolver视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" /> <!--根据自己目录结构灵活设置-->
<property name="suffix" value=".jsp" />
</bean>
<!-- 4.扫描业务代码,即web相关的bean(扫描controller就行,可多扫但不能漏掉需要的部分) -->
<context:component-scan base-package="com.wsx.controller" />
</beans>
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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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
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">
<!--
@整合Service层
该配置文件是由 applicationContext.xml 引入,再交给Spring管理
-->
<!-- 1.扫描service下的包 -->
<context:component-scan base-package="com.wsx.service"></context:component-scan>
<!-- 配置事声明式务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!--
1.配置事物通知,结合AOP实现事务的织入
-->
<tx:advice id="myAdvice" transaction-manager="transactionManager">
<!--配置事物的属性
标签属性介绍:
name:可以使用*通配符,表示专门给某个或者某类方法配置事物约束
isolation:指定事物的隔离级别,默认是default,表示使用数据库的默认隔离级别
propagation:指定事物传播行为,REQUIRED,表示一定有事物,增删改的选择,查询方法可以选择SUPPORT
read-only:用于指定事物是否只读,默认是false,表示可以读写,TRUE表示只读
timeout:用于指定事物的超时时间。默认-1表示永不超时,指定数值时一面,以秒为单位
rollback-for:用来指定一个异常,产生该异常时,回滚,不指定时任何异常都回滚
no-rollback-for:用来指定一个异常,产生该异常时不会滚回滚,不指定时任何异常都回滚
-->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
<!-- <tx:method name="select*" propagation="REQUIRED"/> 查询相关的方法-->
</tx:attributes>
</tx:advice>
<!--2.配置事务切入-->
<aop:config>
<aop:pointcut id="myPointCut" expression="execution(* com.wsx.dao.*.*(..))"/>
<aop:advisor advice-ref="myAdvice" pointcut-ref="myPointCut"/>
</aop:config>
</beans>
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--该总配置文件在web.xml中引入,并交给Spring管理-->
<import resource="spring-dao.xml"></import>
<import resource="spring-mvc.xml"></import>
<import resource="spring-service.xml"></import>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--整合SpringMVC-->
<!--启动Spring,配置DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--指定DispatcherServlet的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<!--一定要注意:我们这里加载的是总的配置文件(总配置文件再引入其他文件);(文件名规范)也可以直接通配符引入多个文件-->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--
将前端控制器Dispatcherservlet的初始化时间提前到服务器启动时
作为框架的核心组件,在启动过程中有大量的初始化操作要做
而这些操作放在第一次请求时才执行会严重影响访问速度
因此需要通过此标签将启动控制DispatcherServlet的初始化时间提前到服务器启动时
即以下设置为 1
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--
设置springMVC的核心控制器所能处理的请求的请求路径
/ 所匹配的请求可以是/login或.html或.js或.css方式的请求路径
但是 / 不能匹配.jsp请求路径的请求:
因为jsp本身就是一个Servlet,所以请求jsp时已经有特定的Servlet来处理该请求了(就是它自己)
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--容器加载监听器(启动项目会报错为解决)-->
<!-- <listener>-->
<!-- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>-->
<!-- </listener>-->
<!--乱码过滤:encodingFilter-->
<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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Session过期时间 /分钟数-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
总结如下:
我这里直接将单个的框架与整合后的进行比较,进而来更好的理解SSM框架
一.整合MyBatis:
在测试类实现MyBatis进行与数据库交互时Test类书写如下:
@Test
public void selectStudents() throws IOException {
//1.加载mybatis核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//2.获取SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.得到执行sql的对象SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.执行sql语句
List<Student> list = sqlSession.selectList("com.edu.cq.dao.StudentMapper.selectStudents");
//5.关闭数据库会话
sqlSession.close();
}
对比上面的步骤:
ssm中如何写Test类
ssm将整合的几个配置文件都交给了IOC,例如ssm的Test类如下:
@Test
public void A(){
//spring-dao.xml 和applicationContext.xml 都可以(applicationContext.xml引入了spring-dao.xml的)
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
PurchaseMapper purchaseMapper = context.getBean("purchaseMapper", PurchaseMapper.class);
......
}
获取获取SqlSessionFactory对象也交给了spring
在ssm整合在 spring-dao.xml有如下配置:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--
配置SqlSessionFactory对象,交给SpringIOC
(对比学习MyBatis Test类中那几个步骤需要的东西来理解)
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池:dataSource -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置(绑定)MyBaties全局配置文件:mybatis-config.xml(里面指定了mapper文件的位置) -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--
上面配置SqlSessionFactory,并指定了mapper文件的位置,接下来还需指明接口
配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 (动态代理方式)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.wsx.dao"/>
</bean>
整合MyBatis的核心点基本上就是这些了。
二.整合SpringMVC:
整合SpringMVC配置的文件就没有太大的区别了。唯一的区别,或者说需要注意的就是:
在web.xml中配置SpringMVC的前端控制器Dispatcherservlet时我们这里加载的是总的配置文件(总配置文件中引入的整合Mybati所需的配置文件以及其他配置文件)如下:
<!--指定DispatcherServlet的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<!--一定要注意:我们这里加载的是总的配置文件(总配置文件再引入其他文件);(文件名规范)也可以直接通配符引入多个文件-->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>