1.前期准备
一、导入坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
二、创建Spring配置类
功能:使用SpringConfig配置类
替代applicationContext.xml
// 标识为注解类(替代application.xml)
@Configuration
// 开启注解扫描,扫描除Controller包以外所有的包
@ComponentScan(value = "com.itheima",
excludeFilters = @ComponentScan.Filter(
type = FilterType.ANNOTATION,
classes = Controller.class
)
)
public class SpringConfig {
}
- @Configuration
该注解在类上,使得这个类的功能同于一个bean xml配置文件,可以在这个类中管理创建Bean。 - @ComponentScan
该注解默认会扫描该类所在的包下所有的配置类,相当于之前的 <context:component-scan>
回顾以往xml的配置
<!-- 开启注解扫描 -->
<context:component-scan base-package="cn.itcast.usermanage.service"/>
2.Spring整合MyBatis
一、在Spring配置类中引入mybatis配置类
@Configuration
@ComponentScan(value = "com.itheima",
excludeFilters = @ComponentScan.Filter(
type = FilterType.ANNOTATION,
classes = Controller.class
)
)
@PropertySource("jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
public class SpringConfig {
}
二、注解详解
@PropertySource注解
通过@PropertySource注解可以将properties配置文件中的key/value存储到Spring的Environment中,Environment接口提供了方法去读取配置文件中的值,参数是properties配置文件中定义的key值。
当然了,也可以使用@Value注解用${}
占位符为bean的属性注入值。
回顾以往xml的配置
<!-- 加载外部的properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
@Import注解
引入其他的配置类,需要在主配置类里引用,@Import(SecondJavaConfig.class)
回顾以往是怎么读取其他Spring配置文件的
1.将Spring主配置文件、Spring整合mybatis的配置文件、Spring整合事务的配置文件都统一放在spring文件夹下,并有统一的命名规范
2.初始化Spring容器时,读取这些文件,构造一个完整的Spring容器
mybatis、transaction这些文件都可以写到主配置中,但是为了区分功能(解耦),所以各自定义了自己的配置文件
在注解开发中,我们可以将其他配置类引入到主配置类中,这样只要读取主配置类即可
三、添加jdbc.properties
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/my_database
jdbc.username=root
jdbc.password=root
2.1 Spring注册数据源(dataSource)
public class JdbcConfig {
@Value("${jdbc.driverClass}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
mybatis的底层是jdbc,mybatis是对jdbc的封装,此处我们将数据源的配置放到jdbc配置类中(其实也能放到mybatis的配置类,效果一样)
@Bean
注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。
类同于
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
另一种方式:如果这种方式不能注入,则可以使用这个方法
@PropertySource({"classpath:/jdbc.properties"})//指定配置文件classPath
@Component
@Data
public class JdbcConfig {
@Value("${jdbc.driverClass}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
}
然后在初始化dataSource时,注入这个对象
// 注入数据源
@Bean
public DataSource dataSource(JdbcConfig jdbcConfig) {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(jdbcConfig.getDriver());
dataSource.setUrl(jdbcConfig.getUrl());
dataSource.setUsername(jdbcConfig.getUsername());
dataSource.setPassword(jdbcConfig.getPassword());
return dataSource;
}
2.2 Spring整合mybatis(添加mybatis配置类)
- 配置SqlSessionFactoryBean
- 注入数据源
- 设置全局配置(此处设置了别名)
- 配置MapperScannerConfigurer
public class MybatisConfig {
// 配置SqlSessionFactoryBean
@Bean
public SqlSessionFactoryBean SqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
// 注入数据源
factoryBean.setDataSource(dataSource);
// 扫描类型别名
factoryBean.setTypeAliasesPackage("com.itheima.domain");
return factoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer msc = new MapperScannerConfigurer();
// 扫描mapper接口
msc.setBasePackage("com.itheima.dao");
return msc;
}
}
2.2.1 SqlSessionFactoryBean
一、回顾mybatis怎么初始化SqlSessionFactory
在没有引入Spring概念时,我们是手动构建SqlSessionFactory,这个过程比较麻烦,现在我们有了Spring
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
// 读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
// 构建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 获取对应mapper
OrderMapper orderMapper= sqlSession.getMapper(OrderMapper.class);
Order order = orderMapper.queryOrderWithUser("20140921001");
System.out.println(order);
}
在mybatis-spring的整合包下,存在一个sqlSessionFactoryBean,它是用来在spring容器中生产sqlSessionFactory的工厂Bean
二、回顾Spring整合mybatis(xml配置方式)
1.在applicationContext-mybatis.xml中定义SqlSessionFactoryBean
2.注入数据源以及mybatis全局配置(mybatis-config.xml)
<!-- spring构建sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定mybatis的数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 指定mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
</bean>
2.2.2 MapperScannerConfigurer
MapperScannerConfigurer是为了解决MapperFactoryBean繁琐而生的,有了MapperScannerConfigurer就不需要我们去为每个映射接口去声明一个bean了。大大缩减了开发的效率。
一、回顾以往的mapper扫描
<mappers>
<package name="com.itheima.mapper"/>
</mappers>
2.3 Spring整合事务管理
- 注解开启事务支持
- 注册事务管理器(根据不同的持久化框架)
- 给需要被事务管理的类、方法…添加@Transaction
一、添加注解 @EnableTransactionManagement 开启事务支持
一定要添加这个注解哦@EnableTransactionManagement
@Configuration
@ComponentScan(value = "com.itheima",
excludeFilters = @ComponentScan.Filter(
type = FilterType.ANNOTATION,
classes = Controller.class
)
)
@PropertySource("jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}
二、在jdbc配置类中注册事务管理器
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
// 不同的持久化框架,选择不同的事务管理器
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
不同的持久化框架,需要使用不同的事务管理器
Spring为不同的持久化框架提供了不同PlatformTransactionManager接口实现:
事务 | 说明 |
---|---|
org.springframework.jdbc.datasource.DataSourceTransactionManager | 使用Spring JDBC或iBatis进行持久化数据时使用 |
org.springframework.orm.hibernate5.HibernateTransactionManager | 使用Hibernate5.0版本进行持久化数据时使用 |
org.springframework.orm.jpa.JpaTransactionManager | 使用JPA进行持久化时使用 |
org.springframework.jdo.JdoTransactionManager | 当持久化机制是Jdo时使用 |
org.springframework.transaction.jta.JtaTransactionManager | 使用一个JTA实现来管理事务,在一个事务跨越多个资源时必须使用 |
三、在类、方法上添加事务注解@Transactional
@Transactional
public class BookServiceImpl implements BookService {
.....
}
回顾之前我们是怎么注册事务管理器的
<!-- druid连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/my_database"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- 第一步:定义具体的平台事务管理器(DataSource事务管理器) -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
3.Spring整合SpringMvc
3.1 SpringMvc配置类
@Configuration
@ComponentScan("com.itheima.controller")
// 用来开启支持SpringMvc的一些配置,常配置实现WebMvcConfigurer接口使用,底层是继承了WebMvcConfigurationSupport
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {
}
@EnableWebMvc
有很多作用,这里仅使用其一种作用:开启自动转换json数据的支持
@EnableWebMvc + WebMvcConfigurer替代WebMvcConfigurationSupport,用来扩展配置类的功能,比如实现返回json数据、定义拦截器等等
3.2 初始化Spring、SpringMvc容器
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
// 初始化Spring容器
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
// 初始化SpringMvc容器
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
3.3 响应
一.响应视图
- 需要是@Controller注解
- 方法的返回值是String类型(视图名称)
- 方法上不能添加@ResponseBody注解
@RequestMapping("/toPage")
public String toPage(){
return "page.jsp";
}
二、响应json数据
- 在项目中添加jackson-databind依赖
- 使用@RestController或@ResponseBody注解;
当我们的adatper(适配器)调用handler(controller)中的方法执行结束返回时,便会选择一个合适的HttpMessageConverter将方法返回值转换为一个格式返回给浏览器。默认调用StringHttpMessageConverter,如果需要返回JSON数据,我们就需要调用MappingJackson2HttpMessageConverter
具体的方法调用顺序如下:
3.4 表现层数据封装
我们在进行业务操作后,响应给前端的数据格式可能是不同的,例如
- 增、改、删操作,返回了boolean类型
- 查询操作返回了对象类型
不便于前端对数据的解析,所以一般会设置成统一格式进行返回
设置统一的数据返回结果类
public class Result {
private Object data;
private Integer code;
private String msg;
}
Result类中的字段并不是固定的,可以根据需要自行增减 提供若干个构造方法,方便操作
3.5 全局异常处理器
所有的异常均需抛出到表现层进行处理,但是这样又出现了一个问题:表现层处理异常,每个方法中单独书写,代码书写量大且意义不强!
使用AOP的思维,针对所有@Controller进行异常处理,SpringMvc针对此需求提供了一个异常处理器
全局异常处理器:
集中的、统一的处理项目中出现的异常(使用一个类就能搞定所有的异常)
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(Exception.class)
public Result doException(Exception ex){
return new Result(666,null);
}
}
-
@RestControllerAdvice
声明这个类是用于做异常处理(Spring需要读取到此类) -
@ExceptionHandler
指定拦截的异常
3.6 项目异常处理方案
一、业务异常(BusinessException)
- 不规范的用户行为产生的异常(url没有按标准填写)
- 规范的用户行为产生的异常(例如age是int类型,但是用户传了字符串)
处理方案:发送对应消息传递给用户,提醒规范操作
二、系统异常(SystemException)
- 项目运行过程中可预计且无法避免的异常
处理方案:
- 发送固定消息传递给用户,安抚用户
- 发送特定消息给运维人员、提醒维护
- 记录日期
三、其他异常(Exception)
- 编程人员未预料到的异常
处理方案:
- 发送固定消息传递给用户,安抚用户
- 发送特定消息给编程人员,提醒维护
- 记录日期
3.7 拦截器
;HandlerExecutionChain是一个执行链,当请求到达DispatchServlet时,DispatchServlet根据请求路径到HandlerMapping查询具体的Handler,从HandlerMapping返回给DispatcherServlet,其中包含了一个具体的Handler对象和Interceptors(拦截器集合)。
3.7.1 自定义拦截器
- 实现HandlerInterceptor接口
- 添加@Component将自定义拦截器交给Spring容器管理(方便之后注册)
@Component
public class ProjectInterceptor implements HandlerInterceptor {
/**
* 前置方法,在Handler方法执行之前执行
* 返回值,返回true拦截器放行 false拦截器不通过,后续业务逻辑不再执行
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("拦截器前置方法...");
return true;
}
/**
* 后置方法,在执行完Handler方法之后执行
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("拦截器后置方法");
}
/**
* 完成方法,在视图渲染完成之后执行
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("拦截器完成方法");
}
}
- preHandle
前置方法,在Handler方法执行之前执行,顺序执行 - preHandle
后置方法,在执行完Handler方法之后执行,倒序执行 - afterCompletion
完成方法,在视图渲染完成之后执行,倒序执行
3.7.2 配置拦截器
一、回顾之前我们是怎么在XML中配置拦截器的
需要在springmvc-servlet.xml中配置自定义的拦截器:
<!-- 注册自定义的拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 拦截所有请求 -->
<mvc:mapping path="/**"/>
<!-- 自定义拦截器的全路径 -->
<bean class="cn.itcast.springmvc.interceptors.MyInterceptor1"/>
</mvc:interceptor>
</mvc:interceptors>
二、拦截器路径和Dispatch拦截路径的关系
拦截器是对Dispatch转发请求后的资源进行拦截,所以它的拦截范围必然是基于Dispatch拦截路径的范围
三、使用WebMvcConfigurationSupport替代springmvc-servlet.xml
- 自定义配置类继承WebMvcConfigurationSupport
- 添加@Configuration,标识为配置类
- 需要让Spring容器读取到此配置
- 通过DI注入拦截器对象
- 重写addInterceptors方法,指定拦截器以及拦截路径
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
// 注入拦截器类
@Autowired
private ProjectInterceptor projectInterceptor;
// 配置拦截器(多个拦截器,也都在这里统一配置)
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(projectInterceptor).addPathPatterns("/books/**","/books");
}
// 对资源进行过滤,过滤后的资源不走handler,直接访问
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pic/**").addResourceLocations("/pic/");
}
}
四、让SpringMvc容器读取到这个配置类(很少使用)
在@ComponentScan扫描配置类所在的包(config)
@Configuration
@ComponentScan({"com.itheima.controller", "com.itheima.config"})
@EnableWebMvc
public class SpringMvcConfig {
}
此处不能使用@Import来引入SpringMvcSupport.class,而应该使用@ComponentScan
- @Import引入配置类,只是为了区分功能模块(不同的配置类中管理自己业务的bean),它的作用只能往容器中注入bean(MybatisConfig、JdbcConfig所有的方法都是为了往容器中生成bean)
- @ComponentScan是让容器来扫描,会根据实现的接口来装载组件
SpringMvcSupport类跟SpringMvcConfig类是一样的,我们甚至可以把SpringMvcSupport类中的功能全部迁移到SpringMvcConfig类
五、最简约的方法:在SpringMvc配置类中直接定义拦截器
在spring中配置webMvc有两种方法
- 一种是继承WebMvcConfigurationSupport
- 另一种方式就是继承WebMvcConfigurer,但是要多加一个@EnableWebMvc注解。
我们需要改造一下SpringMvcConfig类
- 实现WebMvcConfigurer接口
- 添加@EnableWebMvc注解
@Configuration
@ComponentScan({"com.itheima.controller"})
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {
// 注入拦截器
@Autowired
private ProjectInterceptor projectInterceptor;
// 设置拦截器(如果是拦截器链则按顺序执行),一个拦截器可配置多个拦截路径
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(projectInterceptor).addPathPatterns("/books/**","/books");
}
// 设置访问过滤
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pic/**").addResourceLocations("/pic/");
}
}
WebMvcConfigurationSupport 和 WebMvcConfigurer 区别
3.7.3 拦截器和filter过滤器的区别
- 归属不同:filter属于Servlet技术,拦截器属于SpringMvc技术
- 拦截内容不同:Filter对所有访问进行增强,Interceptor仅针对SpringMVC的访问进行增强(DispathServlet设置的拦截路径)