1. 介绍
Spring介绍
- 学习视频:https://www.bilibili.com/video/BV1WE411d7Dv
- 笔记是B站狂神说相关视频的学习笔记
- Rod Johnson是Spring Framework的创始人。Spring的理念:使Java企业级开发更加简单
- 官网:https://spring.io/projects/spring-framework#overview
- 优点:一个开源的免费的容器(框架),其**最重要的特点是IOC,AOP,和支持事务的处理(面试被问到过)**
- 依赖包:使用
spring-webmvc
可以导入学习的所有依赖包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
Spring组成(面试)
学习:https://blog.csdn.net/qq_42773863/article/details/81462360
- Spring Core:Core包是框架的最基础部分,并提供依赖注入(Dependency Injection)管理Bean容器功能
- Spring Context:Core模块的BeanFactory使Spring成为一个容器,而上下文模块使它成为一个框架。这个模块扩展了BeanFactory的概念,增加了对国际化(I18N)消息、事件传播以及验证的支持。另外,这个模块提供了许多企业服务,例如电子邮件、JNDI访问、EJB集成、远程以及时序调度(scheduling)服务。也包括了对模版框架例如Velocity和FreeMarker集成的支持。
- Spring AOP:Spring在它的AOP模块中提供了对面向切面编程的丰富支持。例如方法拦截器(method-interceptors)和切点(pointcuts),可以有效的防止代码上功能的耦合,这个模块是在Spring应用中实现切面编程的基础。
- Spring DAO:对JDBC进行了抽象,大大简化了数据库访问等繁琐的操作;
- Spring ORM:关系映射模块,ORM包为流行的“关系/对象”映射APIs提供了集成层,包括JDO,Hibernate和iBatis(MyBatis)。通过ORM包,可以混合使用所有Spring提供的特性进行“对象/关系”映射,方便开发时小组内整合代码。
- Spring Web:Web上下文模块建立于应用上下文模块之上,提供了一个适合于Web应用的上下文。另外,这个模块还提供了一些面向服务支持。利用Servlet listeners进行IOC容器初始化和针Webapplicationcontext。
- Spring MVC:提供面向Web应用的Model-View-Controller实现。
Spring后续框架
- Spring Boot
- 一个快速的脚手架,基于SpringBoot可以快速的开发单个微服务
- 特点:约束>配置
- Spring Cloud
- 基于SpringBoot实现的完整的微服务开发,是目前的主流
- 特点:完整的微服务框架
2 IOC
IOC的推导
- 之前的Web工程需要Dao,DaoImpl,Service,ServiceImpl,Controller实现应用,但如果代码量过大,变更需求过多,修改一次代码需要更改关联的更多代码,成本十分昂贵
- 假设,我们不在代码中=new XXimpl,而是通过接口的set方法设值,让程序员不用再去管理对象的创建
- 于是,使用了set注入后,程序不再具有主动权,而是变成了被动接受的对象=IOC原型
- 明确概念:IOC是一种思想,DI(依赖注入)是IOC的实现的一种方式,两者不完全相同
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ez15T5YJ-1596418662221)(E:\Java\markdown_notes\photos\image-20200420233451656.png)]
初试application
- import:多人开发,导入多个application配置文件
- bean:创建对象
- alias:取对象的别名,但在bean中直接使用name=XX,比单独使用alias更推荐使用
构造器注入
默认是使用无参构造创建bean
如果没有无参构造,就必须使用< constructor-arg />
指定构造器
总结:在配置文件里面注册bean的时候,就已经实例化了
属性注入
原理:通过Setter方法注入的。同时明白什么DI(依赖注入的概念)
依赖:bean的对象创建依赖于Spring容器来实现
注入:bean对象的所有属性由Spring容器来注入
application.xml
- 学习各种基本类型,引用类型注入,扩展补充:p命令,c命令简化注入(需要导入约束),但使用的很少
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置bean的成员属性-->
<bean id="addressRef" class="com.pojo.Address">
<property name="address" value="中国贵州"/>
</bean>
<!--各种数据类型的注入-->
<bean id="student" class="com.pojo.Student">
<!--配置String类型-->
<property name="name" value="李四"/>
<!--配置另一个bean-->
<property name="address" ref="addressRef"/>
<!--配置数组-->
<property name="books">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>三国演义</value>
</array>
</property>
<!--配置List-->
<property name="hobbies" >
<list>
<value>学习</value>
<value>打球</value>
<value>听歌</value>
</list>
</property>
<!--配置map-->
<property name="card">
<map>
<entry key="身份证" value="1"/>
<entry key="银行卡" value="2"/>
</map>
</property>
<!--配置set-->
<property name="games">
<set>
<value>LOL</value>
<value>BOB</value>
</set>
</property>
<!--NUll-->
<property name="wife">
<null/>
</property>
<!--properties-->
<property name="properties">
<props>
<prop key="url">www.baidu.com</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>
<!--p注入:通过setter注入属性-->
<bean id="hello" class="com.pojo.Hello" p:str="p标签注入,是通过setter注入的"/>
<!--c注入:通过有参构造器注入属性-->
<bean id="helloAndC" class="com.pojo.Hello" c:str="c标签注入,是通过构造器注入的" />
</beans>
Java配置application
- 普通开发很少使用,但是各种框架源码大量使用
@Configuration
public class MyConfig {
/**
* 方法名= bean id ;返回值=bean 的class
*/
@Bean
public User beanId() {
return new User();
}
}
@Component
public class User {
@Value("张三")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
作用域
Scope | Description |
---|---|
singleton | (默认)为每个Spring IoC容器将单个bean定义作用于单个对象实例。 |
prototype | 每个bean都产生一个新的对象实例 |
request | 将单个bean定义的范围限定为单个HTTP请求的生命周期。也就是说,每个HTTP请求都有自己的bean实例,这些实例是在单个bean定义的基础上创建的。仅在web感知的Spring“ApplicationContext”的上下文中有效。 |
session | 将单个bean定义定义为HTTP“会话”的生命周期。仅在web感知的Spring“ApplicationContext”的上下文中有效。 |
application | 将单个bean定义的范围扩展到“ServletContext”的生命周期。仅在web感知的Spring“ApplicationContext”的上下文中有效。 |
websocket | 将单个bean定义的范围扩展到“WebSocket”的生命周期。仅在web感知的Spring“ApplicationContext”的上下文中有效。 |
自动装配
- 不用显示配置bean,添加约束后,Spring会在上下文中自动寻找,并自动给bean装配属性
- 三种装配方式
- xml中显示装配
- 自动装配
- java装配:=前面的 “Java配置application”
bean中的自动装配
- byName:bean的id = 自动注入的成员属性setXXX一样
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qtFC0UkR-1596418662230)(E:\Java\markdown_notes\photos\image-20200421132928467.png)]
- byType:bean中的class和成员变量的类型一致
注解实现自动装配
- 导入注解约束
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
- @Autowired+@Qualifier=@Resource(name = “xx”)
-
使用:直接在成员属性上使用,也可以在set上使用
-
原理:通过反射去xml中寻找成员类型 = class的bean,并自动装配;
-
默认装配不能为空:可以使用
@Autowired(required = false)
指定为空 -
多个相同bean的class:使用
@Qualifier(value = "dog1")
-
@Autowired+@Qualifier=@Resource(name = “xx”)
区别- 相同点:都是自动装配配置
- 不同点:
@Autowired+@Qualifier
通过byType=class来查找;@Resource(name = “xx”)
默认通过byname=id来查找,如果没找到,接着用byType=class来查找
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--初识Spring中的bean,使用Spring来创建对象,这些对象称为bean,是Spring通过set方法来创建的:
bean id/name = new class
-->
<bean id="cat" class="com.pojo.Cat"/>
<bean id="dog" class="com.pojo.Dog"/>
<bean id="hello" name="hello2" class="com.pojo.Hello">
<constructor-arg index="0" value="你好,Spring"/>
</bean>
<!--alias取对象的别名,但是name也可以取别名,更方便-->
<alias name="hello" alias="hello1"/>
<!--import导入另一个.xml配置-->
<import resource="application1.xml"/>
<!--bean中使用autowired-->
<!--byName:通过setXXX名字去匹配,原理是Name id= SetXXX-->
<bean id="people1" class="com.pojo.People" autowire="byName" scope="prototype">
<property name="name" value="people1"/>
</bean>
<!-- byType:通过成员属性去匹配,缺点是class必须唯一,否则找不到-->
<!-- <bean id="people2" class="com.pojo.People" autowire="byType" scope="prototype">
<property name="name" value="people2"/>
</bean>-->
<!--最简单:使用注解配置自动装配-->
<context:annotation-config />
<bean id="peopleAnnotation" class="com.pojo.PeopleAnnotation"/>
<bean id="dog1" class="com.pojo.Dog"/>
</beans>
注解开发
导入aop包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
导入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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--注解配置-->
<context:annotation-config/>
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.ssl.pojo"/>
</beans>
@Component和@Value
- 注解注入bean组件:
@Component
,不用手动去xml中配置bean- component三大衍生注解
- @Repository:对应dao层
- @Service:对应service层
- @Controller:对应controller层
- component三大衍生注解
- 注入成员属性:
@Value("张三")
- 作用域:
@Scope(value="prototype")
/*
@Component = <bean id= "user class="com.ssl.pojo.User" />
@Value("张三") = 通过setter方法区赋值
*/
@Component
@Scope(value = "prototype")
public class User {
@Value("张三")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
xml配置和注解开发
- xml:用来配置Spring一些需求,但bean使用注解配置
- 注解:只负责完成bean的创建和属性的注入
3 代理模式
1 静态代理
2 动态代理
- 动态代理分为:1 基于接口的;2 基于类的动态代理
- 基于接口的:JDK动态代理
- 基于类的的:cglib
- 基于java字节码:Javasist
- 学习两个类:Proxy;InvocationHandler(调用处理器)
//学习动态代理类的实现
public class ProxyInva implements InvocationHandler {
//1 实现被代理的接口
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//2 获得代理对象,通过Proxy.newProxyInstance
public Object getProxy() {
return Proxy.newProxyInstance(
this.getClass().getClassLoader(),
rent.getClass().getInterfaces(),
this);
}
//3 处理代理对象,被返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
beforeSee();
//激活被代理角色的行为
Object invoke = method.invoke(rent, args);
afterSee();
return invoke;
}
//动态代理原型:在invoke前后添加的方法就是aop原型
public void beforeSee(){
System.out.println("提前看房");
}
public void afterSee(){
System.out.println("过后看房");
}
}
//动态代理模版
public class ProxyInvaObject implements InvocationHandler {
//1 创建抽象接口,需要set方法实现反射
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//2 代理方法,Spring自动实现中介角色
public Object getProxy() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}
//3 实现抽象接口的实体方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
addMethod(method.getName());//反射的强大之处
//方法.invoke(接口名,参数)
return method.invoke(target, args);
}
//4 添加的功能,学习反射的强大之处
private void addMethod(String msg) {
System.out.println("执行了" + msg + "方法");
}
}
//动态代理的调用
public class Client {
public static void main(String[] args) {
//真实角色
Rent host = new Host();
//代理角色
ProxyInva proxyInva = new ProxyInva();
//代理角色设置真实角色实现的抽象接口
proxyInva.setRent(host);
//代理角色获得Rent代理类
Rent proxy = (Rent) proxyInva.getProxy();
//由proxy动态代理调用被代理的接口方法
proxy.rent();
}
}
4 AOP
原理图
- aop:不改变原有代码情况下,增加一些功能
- 原理图:各种名词请反复看
Spring实现AOP
- 方式一:无需切面,直接实现InvocationHandler接口
- 方式二:自定义切面,其中编写需要的通知方法
- 方式三:注解配置切面,使用@Aspect
<!--aop依赖-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--AOP配置1-->
<bean id="beforeLog" class="log.beforeLog"/>
<bean id="userImpl1" class="service.UserServiceImpl1"/>
<aop:config>
<!--切入点,expression是被切入的类中的什么方法,这里是万能的切入点-->
<aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl1.*(..))"/>
<!--环绕通知=自动前后都增强-->
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
</aop:config>
<!--AOP配置2-->
<bean id="diyPoint" class="diyAop.DiyPointCut"/>
<bean id="userImpl2" class="service.UserServiceImpl2"/>
<aop:config>
<!--定义切面-->
<aop:aspect ref="diyPoint">
<!--切入点-->
<aop:pointcut id="pointcut1" expression="execution(* service.UserServiceImpl2.*(..))"/>
<!--前后通知-->
<aop:before method="before" pointcut-ref="pointcut1"/>
<aop:after method="after" pointcut-ref="pointcut1"/>
</aop:aspect>
</aop:config>
<!--AOP配置3:注解aop配置-->
<aop:aspectj-autoproxy/>
<bean id="userImpl3" class="service.UserServiceImpl3"/>
<bean id="anonCut" class="anon.AnonPointCut"/>
</beans>
//aop配置1:方法前通知=MethodBeforeAdvice
public class beforeLog implements MethodBeforeAdvice {
/**
*
* 前置增加日志功能
* @param method 被aop增强的方法
* @param args method形参
* @param target method所在的类
*/
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
String targetName = target.getClass().getName();
String methodName = method.getName();
System.out.println(targetName + ":的[" + methodName + "]方法被执行了");
}
}
//aop配置2
public class DiyPointCut {
public void before() {
System.out.println("=====方法前=====");
}
public void after() {
System.out.println("=====方法后=====");
}
}
//aop配置3:注解定义切面
@Aspect
public class AnonPointCut {
//切入点1
@Before("execution(* service.UserServiceImpl3.*(..))")
public void before() {
System.out.println("Anon=====方法前=====");
}
//切入点2
@After("execution(* service.UserServiceImpl3.*(..))")
public void after() { System.out.println("Anon=====方法后=====");
}
//环绕通知
@Around("execution(* service.UserServiceImpl3.*(..))")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕前");
joinPoint.proceed();
System.out.println("环绕后");
/*
环绕前
Anon=====方法前=====
增加了一个用户
环绕后
Anon=====方法后=====
*/
}
}
5 原生Mybatis回顾
步骤:
- mybatis-config.xml
- 配置文件
- 测试
1 依赖包
<?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">
<parent>
<artifactId>root</artifactId>
<groupId>com.ssl</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.ssl</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--测试包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<!-- spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- aop织入包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
<!--maven静态资源过滤-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
2 配置文件
- 编写实体类
@Data
public class User {
private int id;
private String name;
private String pwd;
}
- 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>
<!--使用别名-->
<typeAliases>
<package name="com.ssl.pojo"/>
</typeAliases>
<!--原生Mybatis配置-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!--全部都要被下来-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments>
<!--绑定XXXMapper-->
<mappers>
<mapper class="com.ssl.dao.UserMapper"/>
</mappers>
</configuration>
- 编写接口和mapper.xml
public interface UserMapper {
public List<User> getUsers();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ssl.dao.UserMapper">
<select id="getUsers" resultType="User">
select * from mybatis.user;
</select>
</mapper>
3 测试
spring-mybatis就是简化了这个配置,但是原理没变
public class MyTest {
@Test
public void getUsers() throws IOException {
String resources = "mybaits-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resources);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.getUsers();
System.out.println(users);
}
}
6 Mybatis-Spring
- 概念:MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和
SqlSession
并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的DataAccessException
。最终,可以做到应用代码不依赖于 MyBatis,Spring 或 MyBatis-Spring。
实现一:
- 在Spring中配置dataSource、sqlSessionFactory、sqlSessionTemplate
- spring-dao.xml和apllication.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--Spring配置dataSource:使用Spring的数据源配置mybatis配置-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</bean>
<!--sqlSessionFactory:官网Mybatis-Spring入门上复制过来-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--加载Mybatis配置-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--指定mapper路径-->
<property name="mapperLocations" value="com/ssl/dao/*.xml"/>
</bean>
<!--sqlSessionTemplate-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!--构造器注入,不能使用-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="spring-dao.xml"/>
<!--实现一-->
<bean id="userMapperImpl" class="com.ssl.dao.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
</beans>
- 实现类注入sqlSession
public class UserMapperImpl implements UserMapper {
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> getUsers() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.getUsers();
}
}
实现二:
- spring-dao,xml可以减少sqlSessionTemplate配置,通过实现类中继承
extends SqlSessionDaoSupport
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
@Override
public List<User> getUsers() {
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
return users;
}
}
- application.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="spring-dao.xml"/>
<!--实现二-->
<bean id="userMapperImpl2" class="com.ssl.dao.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
测试
public class MyTest {
@Test
public void getUsers2() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
UserMapper userMapper = context.getBean("userMapperImpl", UserMapper.class);
List<User> users = userMapper.getUsers();
System.out.println(users);
}
@Test
public void getUsers3() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
UserMapper userMapper = context.getBean("userMapperImpl2", UserMapper.class);
List<User> users = userMapper.getUsers();
System.out.println(users);
}
}
7 事务
- 概念:就一句话,要么都成功,要么都失败;在项目中十分重要,确报项目的完整性和一致性
ACID原则(面试高频)
- 原子性:一个操作,要么都成功,要么都失败
- 一致性:一个事务前后数据一致。无论怎么转账,总数1000不会变
- 隔离性:多个业务操作同一个资源,防止数据损坏
- 持久性:事务一旦提交,无论系统发生什么问题,结果都不会改变,被持久化进数据库中
Spring中的事务管理
- 声明式事务:AOP注入
- 编程式事务:需要改变原有代码,在源码上增加try-catch-final
实现声明式事务
7种propagation
(面试高频)
学习:https://blog.csdn.net/soonfly/article/details/70305683
名称 | 特性 |
---|---|
required(默认) | 支持当前事务,如果没有事务,就新建一个事务 |
support | 支持当前事务,如果没有事务,就不执行事务 |
mandatory | 支持当前事务,如果没有事务,就抛出异常 |
required_new | 新建事务,如果当前有事务,就将当前事务挂起 |
not_supported | 以非当前事务执行操作,如果当前有事务,就将当前事务挂起 |
never | 以非当前事务执行操作,如果当前有事务,就抛出异常 |
nested | 支持当前事务,如果当前事务存在,则实行一个嵌套事务,如果没有事务,就新建一个事务 |
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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!--Spring配置dataSource:使用Spring的数据源配置mybatis配置-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</bean>
<!--sqlSessionFactory:官网Mybatis-Spring入门上复制过来-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--加载Mybatis配置-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--指定mapper路径-->
<property name="mapperLocations" value="com/ssl/dao/*.xml"/>
</bean>
<!--sqlSessionTemplate-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!--构造器注入,不能使用-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--声明式事务开启-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
<!--配置事务的通知,需要导入约束-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--为哪些方法配置事务通知-->
<tx:attributes>
<tx:method name="addUser" propagation="REQUIRED"/>
<tx:method name="deleteUser" propagation="REQUIRED"/>
<tx:method name="updateUser" propagation="REQUIRED"/>
<!--查询就不需要事务支持-->
<tx:method name="queryUser" read-only="true"/>
<!--所有方法都支持事务-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置aop-->
<aop:config>
<aop:pointcut id="txPointCUt" expression="execution(* com.ssl.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCUt"/>
</aop:config>
</beans>
接口配置
public interface UserMapper {
public List<User> getUsers();
public int addUser(User user);
public int deleteUser(int id);
}
mappper.xml配置
- 删除操作,手动模拟失败
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ssl.dao.UserMapper">
<select id="getUsers" resultType="User">
select * from mybatis.user;
</select>
<!--添加-->
<insert id="addUser" parameterType="user">
insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
<!--模拟删除失败-->
<delete id="deleteUser" parameterType="int">
deletes from mybatis.user where id=#{id}
</delete>
</mapper>
实现接口
public class UserMapperImpl implements UserMapper {
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> getUsers() {
User user = new User(5, "小宋", "123456");
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
//模拟一组添加和删除的操作,保证两个操作同时成功,不能单独一个操作成功;
//但是删除操作的sql语句故意写错
mapper.addUser(user);
mapper.deleteUser(user.getId());
return mapper.getUsers();
}
@Override
public int addUser(User user) {
return sqlSessionTemplate.getMapper(UserMapper.class).addUser(user);
}
@Override
public int deleteUser(int id) {
return sqlSessionTemplate.getMapper(UserMapper.class).deleteUser(id);
}
}
测试
- 删除操作肯定失败,查看数据库是否添加成功;没有添加成功=事务开启成功
public class MyTest {
@Test
public void getUsers2() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
UserMapper userMapper = context.getBean("userMapperImpl", UserMapper.class);
List<User> users = userMapper.getUsers();
System.out.println(users);
}
}
8 Spring重点
- 注解开发
- Aop配置和反射
- 声明式事务开启
- 整合Mybatis和MVC