SSM 整合
SSM 整合
JinSSM 概念
在项目中:
- SpringMVC 框架负责控制层
- Spring 框架负责整体和业务层的声明式事务管理
- MyBatis 框架负责数据库访问层
实施:通过编写配置文件,实现 SpringIoC 容器接管一切组件
本质上说,整合就是将三层架构和框架核心API组件交给SpringIoC容器管理
一个容器可能就够了,但是我们常见的操作是创建两个IoC容器(web容器和root容器),组件分类管理
总结:
容器名 | 盛放组件 |
---|---|
web容器 | web相关组件(controller,springmvc 核心组件) |
root容器 | 业务和持久层相关组件(service,aop,tx,dataSource,mybatis,mapper 等) |
整合实战
导入依赖
需要依赖清单分析:
- spring
- ioc/di: spring-context ,jakarta.annotation-api
- aop:spring-aspects
- tx:spring-tx,spring-tx
- springmvc
- spring-webmvc
- jakarta.jakartaee-web-api
- jackson-databind
- hibernate-validator / hibernate-validator-annotation-processor 8.0.0.Final
- mybatis
- mybatis
- mysql
- pagehelper
- 其他整合需要
- spring-web
- mybatis-spring
- druid
- lombok
- logback
<!-- 打包方法改成 war -->
<packaging>war</packaging>
<properties>
<!-- 声明版本号 -->
<spring.version>6.0.6</spring.version>
<jakarta.annotation-api.version>2.1.1</jakarta.annotation-api.version>
<jakarta.jakartaee-web-api.version>9.1.0</jakarta.jakartaee-web-api.version>
<jackson-databind.version>2.15.0</jackson-databind.version>
<hibernate-validator.version>8.0.0.Final</hibernate-validator.version>
<mybatis.version>3.5.11</mybatis.version>
<mysql.version>8.0.25</mysql.version>
<pagehelper.version>5.1.11</pagehelper.version>
<druid.version>1.2.8</druid.version>
<mybatis-spring.version>3.0.2</mybatis-spring.version>
<jakarta.servlet.jsp.jstl-api.version>3.0.0</jakarta.servlet.jsp.jstl-api.version>
<logback.version>1.2.3</logback.version>
<lombok.version>1.18.26</lombok.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--spring pom.xml依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>${jakarta.annotation-api.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--
springmvc
spring-webmvc 6.0.6
jakarta.jakartaee-web-api 9.1.0
jackson-databind 2.15.0
hibernate-validator / hibernate-validator-annotation-processor 8.0.0.Final
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-web-api</artifactId>
<version>${jakarta.jakartaee-web-api.version}</version>
<scope>provided</scope>
</dependency>
<!-- jsp需要依赖! jstl-->
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>${jakarta.servlet.jsp.jstl-api.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator-annotation-processor -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<!--
mybatis
mybatis / 3.5.11
mysql / 8.0.25
pagehelper / 5.1.11
-->
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- MySQL驱动 mybatis底层依赖jdbc驱动实现,本次不需要导入连接池,mybatis自带! -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${pagehelper.version}</version>
</dependency>
<!-- 整合第三方特殊依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!-- 日志 , 会自动传递slf4j门面-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
</dependencies>
创建数据库
CREATE DATABASE `ssm`;
USE `ssm`;
CREATE TABLE `t_emp`(
emp_id INT AUTO_INCREMENT,
emp_name CHAR(100),
emp_salary DOUBLE(10,5),
PRIMARY KEY(emp_id)
);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("tom",200.33);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("jerry",666.66);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("andy",777.77);
创建实体类
位置:com.ssm.pojo
@Data
public class Employee {
private Integer empId;
private String empName;
private Double empSalary;
}
配置日志
位置:resources/logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<!-- 指定日志输出的位置,ConsoleAppender表示输出到控制台 -->
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- 日志输出的格式 -->
<!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行 -->
<pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 设置全局日志级别。日志级别按顺序分别是:TRACE、DEBUG、INFO、WARN、ERROR -->
<!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
<root level="DEBUG">
<!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
<appender-ref ref="STDOUT" />
</root>
<!-- 根据特殊需求指定局部日志级别,可也是包名或全类名。 -->
<logger name="com.ssm.mybatis" level="DEBUG" />
</configuration>
配置 SpringMVC 控制层
创建配置文件:WebJavaConfig.java (命名随意)
/**
* 1.实现Springmvc组件声明标准化接口WebMvcConfigurer 提供了各种组件对应的方法
* 2.添加配置类注解@Configuration
* 3.添加mvc复合功能开关@EnableWebMvc
* 4.添加controller层扫描注解
* 5.开启默认处理器,支持静态资源处理
*/
@Configuration
@EnableWebMvc
@ComponentScan("com.ssm.controller")
public class WebJavaConfig implements WebMvcConfigurer {
//开启静态资源
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
配置业务层
配置 AOP 切面 / TX 声明事务整合:ServiceJavaConfig.java (命名随意)
/**
* 1. 声明@Configuration注解,代表配置类
* 2. 声明@EnableTransactionManagement注解,开启事务注解支持
* 3. 声明@EnableAspectJAutoProxy注解,开启aspect aop注解支持
* 4. 声明@ComponentScan("com.ssm.service")注解,进行业务组件扫描
* 5. 声明transactionManager(DataSource dataSource)方法,指定具体的事务管理器
*/
@EnableTransactionManagement
@EnableAspectJAutoProxy
@Configuration
@ComponentScan("com.ssm.service")
public class ServiceJavaConfig {
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
配置持久层
整合 mybatis 配置mapper代理对象,连接池和mybatis核心组件配置
mybatis整合思路:
- 需要将 SqlSessionFactory 和 Mapper 实例加入到IoC容器
- 使用 mybatis 整合包提供的 FactoryBean 快速整合
创建数据库连接信息配置
位置:resources/jdbc.properties
jdbc.user=root
jdbc.password=123456
jdbc.url=jdbc:mysql:///ssm
jdbc.driver=com.mysql.cj.jdbc.Driver
数据库配置类
@Configuration
@PropertySource("classpath:jdbc.properties")
public class DataSourceJavaConfig {
@Value("${jdbc.user}")
private String user;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.driver}")
private String driver;
//数据库连接池配置
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setDriverClassName(driver);
return dataSource;
}
}
整合 mybatis中 xml 和配置类整合二选一
结合 xml 配置整合
创建 mybatis 配置文件
位置:resources/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"/>
<!-- 开启logback日志输出-->
<setting name="logImpl" value="SLF4J"/>
<!--开启resultMap自动映射 -->
<setting name="autoMappingBehavior" value="FULL"/>
</settings>
<typeAliases>
<!-- 给实体类起别名 -->
<package name="com.ssm.pojo"/>
</typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--
helperDialect:分页插件会自动检测当前的数据库链接,自动选择合适的分页方式
你可以配置 helperDialect 属性来指定分页插件使用哪种方言
-->
<property name="helperDialect" value="mysql"/>
</plugin>
</plugins>
</configuration>
mybatis 配置类
@Configuration
public class MapperJavaConfig {
/**
* 配置SqlSessionFactoryBean,指定连接池对象和外部配置文件即可
* @param dataSource 需要注入连接池对象
* @return 工厂Bean
*/
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
//实例化SqlSessionFactory工厂
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//设置连接池
sqlSessionFactoryBean.setDataSource(dataSource);
//设置配置文件
//包裹外部配置文件地址对象
Resource resource = new ClassPathResource("mybatis-config.xml");
sqlSessionFactoryBean.setConfigLocation(resource);
return sqlSessionFactoryBean;
}
/**
* 配置Mapper实例扫描工厂,配置 <mapper <package 对应接口和mapperxml文件所在的包
*/
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//设置mapper接口和xml文件所在的共同包
mapperScannerConfigurer.setBasePackage("com.ssm.mapper");
return mapperScannerConfigurer;
}
}
注意:数据库和 mybatis 要分成两个配置类独立配置,互不影响,数据库提取一个配置类,mybatis提取一个配置类
原因:当你在Spring配置类中添加了sqlSessionFactoryBean
和mapperScannerConfigurer
配置方法时,可能会导致@Value
注解读取不到值为null的问题
这是因为SqlSessionFactoryBean
和MapperScannerConfigurer
是基于MyBatis框架的配置,它们的初始化顺序可能会导致属性注入的问题
结合配置类整合
不在保留mybatis的外部配置文件(xml), 所有配置信息(settings、插件、别名等)全部在声明SqlSessionFactoryBean的代码中指定!数据库信息依然使用DruidDataSource实例替代
mapper 配置类
// description: 持久层配置和Druid和Mybatis配置 使用一个配置文件
@Configuration
public class MapperJavaConfigNew {
/**
* 配置SqlSessionFactoryBean,指定连接池对象和外部配置文件即可
* @param dataSource 需要注入连接池对象
* @return 工厂Bean
*/
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
//实例化SqlSessionFactory工厂
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//设置连接池
sqlSessionFactoryBean.setDataSource(dataSource);
//settings [包裹到一个configuration对象,切记别导错包]
org.apache.ibatis.session.Configuration configuration =
new org.apache.ibatis.session.Configuration();
configuration.setMapUnderscoreToCamelCase(true);
configuration.setLogImpl(Slf4jImpl.class);
configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
sqlSessionFactoryBean.setConfiguration(configuration);
//typeAliases
sqlSessionFactoryBean.setTypeAliasesPackage("com.ssm.pojo");
//分页插件配置
PageInterceptor pageInterceptor = new PageInterceptor();
Properties properties = new Properties();
properties.setProperty("helperDialect","mysql");
pageInterceptor.setProperties(properties);
sqlSessionFactoryBean.addPlugins(pageInterceptor);
return sqlSessionFactoryBean;
}
/**
* 配置Mapper实例扫描工厂,配置 <mapper <package 对应接口和mapperxml文件所在的包
*/
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//设置mapper接口和xml文件所在的共同包
mapperScannerConfigurer.setBasePackage("com.ssm.mapper");
return mapperScannerConfigurer;
}
}
容器初始化
配置名 | 对应内容 | 对应容器 |
---|---|---|
WebJavaConfig | controller,springmvc相关 | web容器 |
ServiceJavaConfig | service,aop,tx相关 | root容器 |
MapperJavaConfig | mapper,datasource,mybatis相关 | root容器 |
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
//指定root容器对应的配置类
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {MapperJavaConfig.class, ServiceJavaConfig.class, DataSourceJavaConfig.class };
}
//指定web容器对应的配置类
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebJavaConfig.class };
}
//指定dispatcherServlet处理路径,通常为 /
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
简单测试
查询所有员工信息,返回对应json数据!
controller
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping("list")
public List<Employee> retList(){
List<Employee> employees = employeeService.findAll();
log.info("员工数据:{}",employees);
return employees;
}
}
service
接口
public interface EmployeeService {
List<Employee> findAll();
}
实现类
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
/**
* 查询所有员工信息
*/
@Override
public List<Employee> findAll() {
List<Employee> employeeList = employeeMapper.queryAll();
return employeeList;
}
}
mapper
mapper 接口类
位置:com.ssm.mapper
public interface EmployeeMapper {
List<Employee> queryAll();
}
mapper xml 配置文件
位置:resources/com/ssm/mapper
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ssm.mapper.EmployeeMapper">
<select id="queryAll" resultType="employee">
select emp_id empId,emp_name empName, emp_salary empSalary from t_emp
</select>
</mapper>