本质上说,整合就是将三层架构和框架核心API组件交给SpringIoC容器管理
两个容器,一个容器可能就够了,但是我们常见的操作是创建两个IoC容器(web容器和root容器),组件分类管理
这种做法有以下好处和目的:
总的来说,初始化两个容器在SSM整合中可以实现关注点分离、解耦合、灵活配置等好处。它们各自负责不同的层次和功能,并通过合适的集成方式协同工作,提供一个高效、可维护和可扩展的应用程序架构。
容器名 | 盛放组件 |
---|---|
web容器 | web相关组件(controller,springmvc核心组件) |
root容器 | 业务和持久层相关组件(service,aop,tx,dataSource,mybatis,mapper等) |
两个无关联的 IoC 容器之间组件是无法注入的,而存在父子关系,则子容器可以单向的注入父容器的组件
结论:web容器是root容器的子容器,父子容器关系。这个在源码中可以看到。
配置类的数量不是固定的,但是至少要两个,为了方便编写,我们可以三层架构每层对应一个配置类,分别指定两个容器加载即可
配置名 | 对应内容 | 对应容器 |
---|---|---|
WebJavaConfig | controller,springmvc相关 | web容器 |
ServiceJavaConfig | service,aop,tx相关 | root容器 |
MapperJavaConfig | mapper,datasource,mybatis相关 | root容器 |
在web项目下,我们可以选择web.xml和配置类方式进行ioc配置,推荐配置类。对于使用基于 web 的 Spring 配置的应用程序,建议这样做,如以下示例所示:
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() { //指定root容器对应的配置类
return new Class[]{ServiceJavaConfig.class, MapperJavaConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() { //指定web容器对应的配置类 webioc容器的配置类
return new Class[]{WebJavaConfig.class};
}
@Override
protected String @NonNull [] getServletMappings() { //指定dispatcherServlet处理路径,通常为 /
return new String[]{"/"};
}
}
整合完毕后目录结构:
依赖清单分析
<properties>
<spring.version>6.0.6spring.version>
<jakarta.annotation-api.version>2.1.1jakarta.annotation-api.version>
<jakarta.jakartaee-web-api.version>9.1.0jakarta.jakartaee-web-api.version>
<jackson-databind.version>2.15.0jackson-databind.version>
<hibernate-validator.version>8.0.0.Finalhibernate-validator.version>
<mybatis.version>3.5.11mybatis.version>
<mysql.version>8.0.25mysql.version>
<pagehelper.version>5.1.11pagehelper.version>
<druid.version>1.2.8druid.version>
<mybatis-spring.version>3.0.2mybatis-spring.version>
<jakarta.servlet.jsp.jstl-api.version>3.0.0jakarta.servlet.jsp.jstl-api.version>
<logback.version>1.2.3logback.version>
<lombok.version>1.18.26lombok.version>
<maven.compiler.source>17maven.compiler.source>
<maven.compiler.target>17maven.compiler.target>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>jakarta.annotationgroupId>
<artifactId>jakarta.annotation-apiartifactId>
<version>${jakarta.annotation-api.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>jakarta.platformgroupId>
<artifactId>jakarta.jakartaee-web-apiartifactId>
<version>${jakarta.jakartaee-web-api.version}version>
<scope>providedscope>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>${jackson-databind.version}version>
dependency>
<dependency>
<groupId>org.hibernate.validatorgroupId>
<artifactId>hibernate-validatorartifactId>
<version>${hibernate-validator.version}version>
dependency>
<dependency>
<groupId>org.hibernate.validatorgroupId>
<artifactId>hibernate-validator-annotation-processorartifactId>
<version>${hibernate-validator.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>${pagehelper.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>${mybatis-spring.version}version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>${logback.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>${druid.version}version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${lombok.version}version>
dependency>
dependencies>
位置:resources/logback.xml
<configuration debug="true">
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%npattern>
<charset>UTF-8charset>
encoder>
appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
root>
<logger name="com.ssm.mybatis" level="DEBUG" />
configuration>
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{ServiceJavaConfig.class, MapperJavaConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebJavaConfig.class};
}
@Override
protected String @NonNull [] getServletMappings() {
return new String[]{"/"};
}
}
@ComponentScan("com.ssm.controller")
@EnableWebMvc
@Configuration
public class WebJavaConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable(); // 开启静态资源访问
}
}
@EnableTransactionManagement
@EnableAspectJAutoProxy
@ComponentScan("com.ssm.service")
@Configuration
public class ServiceJavaConfig {
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
主要配置mapper代理对象,连接池和mybatis核心组件配置
mybatis核心api使用回顾:
//1.读取外部配置文件
InputStream ips = Resources.getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
//3.创建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.获取mapper代理对象
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
//5.数据库方法调用
int rows = empMapper.deleteEmpById(1);
System.out.println("rows = " + rows);
//6.提交和回滚
sqlSession.commit();
sqlSession.close();
mybatis核心api介绍回顾:
SqlSessionFactoryBuilder
这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。
因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。 无需ioc容器管理!
SqlSessionFactory
一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,因此 SqlSessionFactory 的最佳作用域是应用作用域。 需要ioc容器管理!
SqlSession
每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。 无需ioc容器管理!
Mapper映射器实例
映射器是一些绑定映射语句的接口。映射器接口的实例是从 SqlSession 中获得的。虽然从技术层面上来讲,任何映射器实例的最大作用域与请求它们的 SqlSession 相同。但方法作用域才是映射器实例的最合适的作用域。
从作用域的角度来说,映射器实例不应该交给ioc容器管理
但是从使用的角度来说,业务类(service)需要注入mapper接口,所以mapper应该交给ioc容器管理
总结
例如,自己实现sqlSessionFactory加入ioc容器:
@Bean
public SqlSessionFactory sqlSessionFactory(){
//1.读取外部配置文件
InputStream ips = Resources.getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
return sqlSessionFactory;
}
过程比较繁琐,为了提高整合效率,mybatis提供了提供封装SqlSessionFactory和Mapper实例化的逻辑的FactoryBean组件,我们只需要声明和指定少量的配置即可
SqlSessionFactoryBean源码展示(mybatis提供):
package org.mybatis.spring;
public class SqlSessionFactoryBean
implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ContextRefreshedEvent> {
//封装了实例化流程
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
//实例化对象逻辑
afterPropertiesSet();
}
//返回对象逻辑
return this.sqlSessionFactory;
}
}
mybatis整合思路总结:
数据库连接信息,位置:resources/jdbc.properties
jdbc.user=root
jdbc.password=root
jdbc.url=jdbc:mysql:///mybatis-example
jdbc.driver=com.mysql.cj.jdbc.Driver
数据库信息以及mapper扫描包设置使用Java配置类处理,mybatis其他的功能(别名、settings、插件等信息)依然在 mybatis-config.xml
配置
mybatis-config.xml
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"/>
<setting name="logImpl" value="SLF4J"/>
<setting name="autoMappingBehavior" value="FULL"/>
settings>
<typeAliases>
<package name="com.ssm.pojo"/>
typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
plugin>
plugins>
configuration>
package com.ssm.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import javax.sql.DataSource;
import java.util.Properties;
/**
* @author Mr.Bear
*/
@PropertySource("classpath:jdbc.properties")
@Configuration
public class MapperJavaConfig {
/**
* 数据库连接池配置
*/
@Bean
public DataSource dataSource(@Value("${jdbc.user}") String user,
@Value("${jdbc.password}") String password,
@Value("${jdbc.url}") String url,
@Value("${jdbc.driver}") String driver){
System.out.println("driver:" + driver);
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setDriverClassName(driver);
return dataSource;
}
/**
* sqlSessionFactory 配置,需要sqlSessionFactory时会通过SqlSessionFactoryBean工厂的 getObject() 方法获取
*/
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
return sqlSessionFactoryBean;
}
/**
* 配置Mapper实例扫描工厂,配置
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//设置mapper接口和xml文件所在的共同包
mapperScannerConfigurer.setBasePackage("com.ssm.mapper");
return mapperScannerConfigurer;
}
}
public interface ScheduleMapper {
List<Schedule> selectList(Schedule schedule);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ssm.mapper.ScheduleMapper">
<select id="selectList" resultType="schedule">
select * from schedule
select>
mapper>
修改配置类中的方法:sqlSessionFactoryBean()
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
// sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
// 配置 setting 标签内容
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);
// 配置别名
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;
}
ResultVO
@AllArgsConstructor
@NoArgsConstructor
@Data
public class ResultVO<T> {
private int code = 200;
private boolean flag = true;
private T data;
public ResultVO(T data) {
this.data = data;
}
}
ScheduleController
@RequestMapping("schedule")
@RestController
public class ScheduleController {
@Autowired
private ScheduleService scheduleServiceImpl;
@RequestMapping("querySchedule")
public ResultVO<List<Schedule>> querySchedule(@RequestBody(required = false) Schedule query) {
return new ResultVO<>(scheduleServiceImpl.querySchedule(query));
}
}
ScheduleServiceImpl
@Service
public class ScheduleServiceImpl implements ScheduleService {
@Autowired
private ScheduleMapper scheduleMapper;
@Override
public List<Schedule> querySchedule(Schedule query) {
PageHelper.startPage(1, 2);
return scheduleMapper.selectList(query);
}
}
补充完整后访问:http://localhost:8080/ssm/schedule/querySchedule
即可得到查询结果