目录
SSM框架整合时三层架构的分工
进行SSM框架整合时,3个框架的分工如下所示。
MyBatis负责与数据库进行交互。
Spring负责事务管理,Spring可以管理持久层的Mapper对象及业务层的Service对象。由于Mapper对象和Service对象都在Spring容器中,所以可以在业务逻辑层通过Service对象调用持久层的Mapper对象。
Spring MVC负责管理表现层的Handler。Spring MVC容器是Spring容器的子容器,因此Spring MVC容器可以调用Spring容器中的Service对象。
SSM框架整合实现思路
下面通过一个图书信息查询案例来描述SSM框架的整合,案例实现思路如下。
- 搭建项目基础结构。首先需要在数据库中搭建项目对应的数据库环境;然后创建一个Maven Web项目,并引入案例所需的依赖;最后创建项目的实体类,创建三层架构对应的模块、类和接口。
- 整合Spring和MyBatis。在Spring配置文件中配置数据源信息,并且将SqlSessionFactory对象和Mapper对象都交由Spring管理。
- 整合Spring和Spring MVC。Spring MVC是Spring框架中的一个模块,所以Spring整合Spring MVC只需在项目启动时分别加载各自的配置即可。
数据准备
CREATE DATABASE ssm;
USE ssm;
CREATE TABLE `tb_book` (
`id` INT(11) ,
`name` VARCHAR(32) ,
`press` VARCHAR(32) ,
`author` VARCHAR(32) );
INSERT INTO `tb_book` VALUES
(1, 'Java EE企业级应用开发教程', '人民邮电出版社', '黑马程序员');
引入项目依赖
(1)Spring相关依赖。spring-context : Spring上下文;spring-tx : Spring事务管理;spring-jdbc : SpringJDBC;spring-test : Spring单元测试;spring-webmvc : Spring MVC核心。 (2)MyBatis相关依赖。mybatis : MyBatis核心;
(3)MyBatis与Spring整合包。mybatis-spring :MyBatis与Spring整合。
(4)数据源相关。druid : 阿里提供的数据库连接池。
(5)单元测试相关的依赖。junit : 单元测试,与spring-test放在一起做单元测试。
(6)ServletAPI相关的依赖。jsp-api : jsp页面使用request等对象;servlet-api : java文件使用request等对象。
(7)数据库相关的依赖。mysql-connector-java : mysql的数据库驱动包。
基本环境逻辑的准备
<?xml version="1.0" encoding="utf8"?>
<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.it</groupId>
<artifactId>Days11</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 声明当前是一个maven的web工程-->
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- web工程,需要servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- dao层-->
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
<!-- 连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.24</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- springmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- spring的ioc相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- spring的aop相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- spring的jdbc相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- spring的事务相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- spring整合单元测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- spring整合mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<source>1.8</source>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!--解决get乱码问题-->
<uriEncoding>utf-8</uriEncoding>
<port>8080</port>
<!-- 虚拟项目名-->
<path></path>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
</project>
Spring和MyBatis的整合步骤
Spring和MyBatis的整合可以分为2步来完成,首先搭建Spring环境,然后整合MyBatis到Spring环境中。框架环境包含框架对应的依赖和配置文件,其中Spring的依赖、MyBatis的依赖、Spring和MyBatis整合的依赖,在项目基础结构搭建时候已经引入到项目中了,接下来,只需编写Spring的配置文件、Spring和MyBatis整合的配置文件即可。
public class MyBatisTest {
public static void main(String[] args) throws Exception{
InputStream inputStream =Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
BookMapper bookMapper=sqlSession.getMapper(BookMapper.class);
Book book=bookMapper.findBookById(1);
System.out.println(book);
}
}
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=root
application-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" 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">
<!--注解扫描-->
<context:component-scan base-package="com.it.service"></context:component-scan>
<!--spring和mybatis整合
:ioc思想
1.数据源
2.sqlSessionFactory
3.mapper对象
-->
<!-- 数据源-->
<!-- 读取外部配置-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
</bean>
<!-- sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="typeAliasesPackage" value="com.it.pojo"></property>
</bean>
<!-- 管理mapper-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="basePackage" value="com.it.dao"></property>
</bean>
</beans>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:application-service.xml"})
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void testFindBookById() {
Book book = bookService.findBookById(1);
System.out.println(book);
}
}
Spring和Spring MVC整合
Spring的配置
之前Spring和MyBatis整合时,已经完成了Spring的配置文件,Spring和Spring MVC整合,只需在项目启动时加载Spring容器和Spring的配置文件即可。在项目的web.xml文件中配置Spring的监听器来加载Spring容器及Spring的配置文件,具体配置如下所示。
<context-param> <param-name>contextConfigLocation</param-name>
<param-value>classpath:application-*.xml</param-value>
</context-param>
<listener> <listener-class>
org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Spring MVC的配置
本案例主要测试SSM整合的情况,因此在Spring MVC的配置文件中只配置SSM整合案例必须的配置。必须配置的项有以下2个。
- 配置包扫描,指定需要扫描到Spring MVC中的Controller层所在的包路径。
- 配置注解驱动,让项目启动时启用注解驱动,并且自动注册HandlerMapping和HandlerAdapter。
在项目的src\main\resources目录下创建Spring MVC的配置文件spring-mvc.xml。Spring-mvc.xml文件配置完成之后,在web.xml中配置Spring MVC的前端控制器,并在初始化前端控制器时加载Spring MVC的配置文件。
application-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">
<!-- 数据源-->
<!-- 读取外部配置-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
</bean>
<!-- sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="typeAliasesPackage" value="com.it.pojo"></property>
</bean>
<!-- 管理mapper-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="basePackage" value="com.it.dao"></property>
</bean>
</beans>
book.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html><head><title>图书信息查询</title></head><body>
<table border="1">
<tr><th>图书id</th><th>图书名称</th>
<th>出版社</th><th>作者</th></tr>
<tr><td>${book.id}</td><td>${book.name}</td>
<td>${book.press}</td>
<td>${book.author}</td></tr>
</table></body>
</html>
@Controller
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping("/book")
public ModelAndView findBookById(Integer id)
{
Book book = bookService.findBookById(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("book.jsp");
modelAndView.addObject("book", book);
return modelAndView;
}
@ResponseBody
@RequestMapping("/demo")
public String demo()
{
return "success";
}
}
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">
<!-- 配置前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- springmvc配置文件的位置-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 初始化启动-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 乱码过滤器-->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<!-- spring和springmvc的整合:让springmvc知道spring容器的位置-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-*.xml</param-value>
</context-param>
</web-app>
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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.alibaba.com/schema/stat"
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.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd">
<!-- 注解扫描-->
<context:component-scan base-package="com.it.controller"></context:component-scan>
<!-- 注解驱动-->
<mvc:annotation-driven/>
<!-- 视图解析器-->
</beans>
纯注解方式整合SSM框架思路
application-dao.xml
application-dao.xml配置文件中配置的内容包含以下4项。
- 读取jdbc.properties文件中的数据连接信息。
- 创建Druid对象,并将读取的数据连接信息注入到Druid数据连接池对象中。
- 创建SqlSessionFactoryBean对象,将并将Druid对象注入到SqlSessionFactoryBean对象中。
- 创建MapperScannerConfigurer对象,并指定扫描的Mapper的路径。
application-service.xml和spring-mvc.xml
application-service.xml配置文件中只配置了包扫描,指定需要扫描到Spring 的Service层所在的包路径。spring-mvc.xml配置文件中配置了Spring MVC扫描的包路径和注解驱动。
web.xml
web.xml配置文件配置了项目启动时加载的信息,包含如下3个内容。
- 使用<context-param>元素加载Spring配置文件application-service.xml和Spring整合Mybatis的配置文件application-dao.xml。
- Spring容器加载监听器。
- 配置Spring MVC的前端控制器。
代码实现
@PropertySource("classpath:jdbc.properties")
@MapperScan("com.it.dao")
public class MyBatisConfig {
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.driver}")
private String driver;
@Bean
public DataSource dataSource()
{
DruidDataSource dataSource=new DruidDataSource();
//设置连接参数
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driver);
return dataSource;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource)
{
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage("com.it.pojo");
return sqlSessionFactoryBean;
}
}
@Configuration//声明当前类是一个配置类
@ComponentScan("com.it.service")
@Import({MyBatisConfig.class})//导入其他配置类
public class SpringConfig {
}
@Configuration
@ComponentScan("com.it.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
public class ServletContainerInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
我人闷了,一个a child container failed start报错搞了我3小时,结果是SpringConfig.class写成了Servlet.class一直没发现。