spring理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.13</version>
</dependency>
优点
- Spring是一个开源的免费的框架(容器)
- Spring是一个轻量级的、非入侵式的框架
- 控制反转(IOC),面向切面编程(AOP)
- 支持事务的处理,对框架整合的支持
Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架
Spring组成
扩展
- Spring Boot
- 一个快速开发的脚手架
- 基于SpringBoot可以快速开发单个微服务
- 预定大于配置
- Spring Cloud
- SpringCloud是基于SpringBoot实现的
现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC。承上启下
弊端:发展了太久之后,违背了原来的理念,配置十分繁琐
IOC理论推导
在以前的业务中,用户的需求可能会影响原来的代码,我们需要根据用户的需求去修改原代码,如果代码量十分大,修改一次的成本过高
使用一个Set接口实现,
private UserDao userDao;
//利用set进行动态实现值的注入
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
- 之前,程序是主动创建对象,控制权在程序猿手上
- 使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象
这种思想,从本质上解决了问题,程序猿不用再去管理对象的创建。系统的耦合性大大降低,可以更加的专注在业务的实现上
IOC本质
控制反转loC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现loC的一种方法,也有人认为DI只是loC的另一种说法。没有loC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是loC容器,其实现方法是依赖注入(Dependency Injection,Dl)。
HelloSpring
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
实体类
package com.hzx.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
配置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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 使用Spring来创建对象 在Spring这些都成为Bean
类型 变量名 = new 类型();
Hello hello = new Hello();
bean = 对象 new Hello();
id = 变量名
class = new 的对象
property 相当于给对象中的属性设置一个值
-->
<bean id="hello" class="com.hzx.pojo.Hello">
<property name="str" value="Spring"></property>
</bean>
</beans>
测试
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象都在Spring中管理了,我们要使用,直接去里面取出来就可以
Hello hello = (Hello)context.getBean("hello");
System.out.println(hello.toString());
}
}
思考问题?
Hello对象是谁创建的?
hello对象是由Spring创建的
Hello对象的属性是怎么设置的?
hello对象的属性是由Spring容器色湖之的
这个过程就叫控制反转;
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的.
反转∶程序本身不创建对象,而变成被动的接收对象.
依赖注入∶就是利用set方法来进行注入的.
IOC是一种编程思想,由主动的编程变成被动的接收.
可以通过newClassPath×mlApplicationContext去浏览一下底层源码.
OK,到了现在,我们彻底不用再程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的loC,一句话搞定:对象由Spring 来创建,管理,装配!
IOC创建对象的方式
- 使用无参构造创建对象,默认
- 使用有参构造创建方法
- 下标赋值
<!--下标赋值--> <bean id="user" class="com.hzx.pojo.User"> <constructor-arg index="0" value="hzx"></constructor-arg> </bean>
- 通过类型创建
<!-- 不建议使用 --> <bean id="user" class="com.hzx.pojo.User"> <constructor-arg type="java.lang.String" value="hzx"></constructor-arg> </bean>
- 通过参数名设置
<!-- 直接通过参数名设置 --> <bean id="user" class="com.hzx.pojo.User"> <constructor-arg name="name" value="hzx"></constructor-arg> </bean>
- 下标赋值
Spring容器,类似于婚介网站。
总结:在配置文件加载的时候,容器中管理的对象就已经被初始化了。
Spring配置说明
别名
<!-- 别名,如果添加了别名可以用原来的或者别名获取 -->
<alias name="user" alias="U"></alias>
Bean的配置
<!--
id:bean的唯一标识符,也就是相当于我们学的对象名
class:bean对象所对应的权限定名:包名+类型
name:也是别名 而且可以同时去多个别名
-->
<bean id="user" class="com.hzx.pojo.User" name="user2 u2,u3;u4" >
</bean>
import
import一般用于团队开发使用,它可以将多个配置文件,导入合并为一个
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="beans1.xml"></import>
<import resource="beans2.xml"></import>
<import resource="beans3.xml"></import>
</beans>
DI依赖注入
构造器注入
Set方式注入
- 依赖注入:Set注入
- 依赖:bean对象的创建依赖于容易
- 注入:bean对象中的所有属性,由容器来注入
【环境搭建】
- 复杂类型
public class Address { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } @Override public String toString() { return "Address{" + "address='" + address + '\'' + '}'; }
- 真实对象
public class Student { private String name; private Address address; private String[] books; private List<String> hobbys; private Map<String,String> card; private Set<String> games; private Properties info; private String wife; public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String[] getBooks() { return books; } public void setBooks(String[] books) { this.books = books; } public List<String> getHobbys() { return hobbys; } public void setHobbys(List<String> hobbys) { this.hobbys = hobbys; } public Map<String, String> getCard() { return card; } public void setCard(Map<String, String> card) { this.card = card; } public Set<String> getGames() { return games; } public void setGames(Set<String> games) { this.games = games; } public Properties getInfo() { return info; } public void setInfo(Properties info) { this.info = info; } public String getWife() { return wife; } public void setWife(String wife) { this.wife = wife; } @Override public String toString() { return "com.hzx.pojo.Student{" + "name='" + name + '\'' + ", address=" + address.toString() + ", books=" + Arrays.toString(books) + ", hobbys=" + hobbys + ", card=" + card + ", games=" + games + ", info=" + info + ", wife='" + wife + '\'' + '}'; } }
- beans.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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="address" class="com.hzx.pojo.Address"></bean> <bean id="student" class="com.hzx.pojo.Student"> <!-- 第一种 普通值 注入 --> <property name="name" value="hzx"></property> <!-- 第二种 Bean注入 ref --> <property name="address" ref="address"></property> <!-- 数组注入 ref --> <property name="books"> <array> <value>红楼梦</value> <value>西游记</value> <value>水浒传</value> <value>三国演义</value> </array> </property> <!--List--> <property name="hobbys"> <list> <value>听歌</value> <value>敲代码</value> <value>看电影</value> </list> </property> <!-- Map --> <property name="card"> <map> <entry key="身份证" value="111111"></entry> <entry key="银行卡" value="111"></entry> </map> </property> <!-- Set --> <property name="games"> <set> <value>英雄联盟</value> <value>王者荣耀</value> </set> </property> <!-- NULL 或者 空值注入 --> <property name="wife"> <null></null> </property> <!-- Properties key value --> <property name="info"> <props> <prop key="学号">2020111</prop> <prop key="性别">男</prop> <prop key="姓名">小鸣</prop> </props> </property> </bean> </beans>
- 测试类
public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Student student = (Student)context.getBean("student"); System.out.println(student.toString()); } }
其它方式注入
P命名空间
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- p命名空间注入 可以直接注入属性值:property -->
<bean id="user" class="com.hzx.pojo.User" p:name="hzx" p:age="22"></bean>
</beans>
导入头文件约束
xmlns:p="http://www.springframework.org/schema/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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--c命名空间注入 通过构造器注入:construct-args-->
<bean id="user2" class="com.hzx.pojo.User" c:name="hzx" c:age="21"></bean>
</beans>
导入头文件
xmlns:c="http://www.springframework.org/schema/c"
注意点:P、C命名空间不能直接使用都要到入xml约束 也就是头文件
Bean作用域
Scope | Description |
singleton | (Default) Scopes a single bean definition to a single object instance for each Spring loC container. |
prototype | Scopes a single bean definition to any number of object instances. |
request | scopes a single bean definition to the lifecycle of a single HTTp request.That is,each HTTP request has its own instance of a beancreated off the back of a single bean definition.only valid in the context of a web-aware Spring ApplicationContext. |
session | Scopes a single bean definition to the lifecycle of an HTTP Session.Only valid in the context of a web-aware Spring ApplicationContext . |
application | scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring Aoolicationlontext . |
websocket | Scopes a single bean definition to the lifecycle of a webSocket . only valid in the context of a web-aware Spring ApplicotionContext . |
- 单例模式(Spring默认机制)
<bean id="user2" class="com.hzx.pojo.User" c:name="hzx" c:age="21" scope="singleton"></bean>
- 原型模式:每次从容器种get的时候,都会产生一个新对象
<bean id="user2" class="com.hzx.pojo.User" c:name="hzx" c:age="21" scope="prototype"></bean>
- 其余的request、session、application、websocket这些只能在web开发种使用
Bean的自动装配
- 自动装配是Spring满足bean依赖一种方式
- Spring会在上下文中自动寻找,并自动给bean装配属性
在Spring中有三种装配的方式
- 在xml中显式地配置
- 在Java中显式地配置
- 隐式地自动装配bean【重要】
测试
ByName自动装配
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
-->
<bean id="people" class="com.hzx.pojo.Person" autowire="byName">
<property name="name" value="hzx"></property>
</bean>
ByType自动装配
<!--
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean
-->
<bean id="people" class="com.hzx.pojo.Person" autowire="byType">
<property name="name" value="hzx"></property>
</bean>
小结:
- byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
- byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致
使用注解实现自动装配
要使用注解须知:
- 导入约束:context约束
- 配置注解的支持:
<?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:annotation-config> </beans>
@Autowired
直接在属性上使用即可,也可以在set方式上使用
使用Autowired我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byName;
科普:
@Nullable 字段标记了这个注解,说明这个字段可以为null
@Autowired(required=false) 如果显式地定义了required为false,说明这个对象可以为null,否则不能为空
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value=" ")去配置@Autowired的使用,指定一个唯一的bean对象注入。
@Resource注解
小结:
@Resource和@Autowired的区别:
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired通过byType的方式实现,而且必须要求这个对象存在。【常用】
- @Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现。如果两个都找不到的情况下,就报错。
- 执行顺序不同:@Autowired通过byType的方式实现,@Resource默认通过byName的方式实现
使用注解开发
在Spring4之后,使用注解开发,必须确认aop的包导入了。
使用注解需要导入context的约束,增加注解的支持。
bean
属性如何注入
衍生的注解
@Component有几个衍生注解,我们在web开发中,会按照MVC三层架构
- dao【@Repository】
- controller【@Controller】
- service【@Serivce】
这四个注解功能都是一样的,都是代表将某个类注册到Spring容器中,装配Bean
自动装配
@Autowired、@Resource
作用域
@Scope
小结
xml与注解:
- xml更加万能,适用于任何场合,维护简单方便
- 注解,不是自己的类使用不了,维护相对复杂
xml与注解的最佳实践:
- xml用来管理bean
- 注解用来完成属性的注入
- 在使用的过程中,只需要注意一个问题,必须让注解生效,就需要开启注解的支持
使用Java的方式配置Spring
现在要完全不使用Spring的xml配置了,全权交给Java来做。
JavaConifg是Spring的一个子项目,在Spring4之后,它成为了核心功能。
实体类
//这里这个注解的意思,说明这个类被Spring接管了 注册到了容器中
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("hzx")//属性注入值
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
Config配置类
//这个也会被Spring容器托管,注册到容器中,因为它本来就是一个@Component
//@Configuration 代表这是一个配置类,就和之前看的beans,xml
@Configuration
@ComponentScan("com.hzx.pojo")
public class MyConfig {
//注册一个bean 就相当于我们之前写的一个bean标签
//这个方法的名字,就当于bean标签中的id属性
//这个方法的返回值,就当于bean标签的class属性
@Bean
public User getUser(){
return new User(); // 就是返回要注入到bean的对象
}
}
测试
public class MyTest {
public static void main(String[] args) {
//如果完全使用了配置类方式去做,只能通过AnnotationConfig上下文获取容器 通过配置类的class对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User getUser = (User)context.getBean("getUser");
System.out.println(getUser.getName());
}
}
代理模式
加深理解AOP
AOP
什么是AOP
AOP (Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
Aop在Spring中的作用
提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等....
- 切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点 (PointCut):切面通知执行的“地点"的定义。
- 连接点(JointPoint) :与切入点匹配的执行点。
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
通知类型 | 连接点 | 实现接口 |
前置通知 | 方法方法前 | org.springframework.aop.MethodBeforeAdvice |
后置通知 | 方法后 | org.springframework.aop.AfterReturningAdvice |
环绕通知 | 方法前后 | org.aopalliance.intercept.MethodInterceptor |
异常抛出通知 | 方法抛出异常 | org.springframework.aop.ThrowAdviece |
引介通知 | 类种增加新的方法属性 | org.springframework.aop.IntroductionInterceptor |
即Aop在不改变原有代码的情况下,去增加新的功能。
使用Spring实现Aop
【重点】使用AOP,需要导入一个依赖包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.8.RC1</version>
</dependency>
环境搭建:
接口:
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
实现类:
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void delete() {
System.out.println("删除了一个用户");
}
@Override
public void update() {
System.out.println("更新了一个用户");
}
@Override
public void select() {
System.out.println("查询了一个用户");
}
}
aop接口实现类:
public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//args: 参数
//target:目标对象
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
//returnValue:返回值
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
}
}
核心配置文件:
<?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">
<!--注册bean-->
<bean id="userService" class="com.hzx.service.UserServiceImpl"></bean>
<bean id="log" class="com.hzx.log.Log"></bean>
<bean id="afterlog" class="com.hzx.log.AfterLog"></bean>
</beans>
方式一:使用原生Spring API实现【主要SpringAPI接口实现】
<!-- 方式一:使用原生Spring API接口 -->
<!-- 配置aop:需要导入aop的约束 -->
<aop:config>
<!-- 切入点 expression:表达式 execution(要执行的位置) -->
<aop:pointcut id="pointcut" expression="execution(* com.hzx.service.UserSericeImpl.*(..))"/>
<!-- 执行环绕增加 -->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"></aop:advisor>
<aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
方式二:自定义来实现AOP【主要是切面定义】
public class DiyPiontCut {
public void before(){
System.out.println("===============方法执行前=================");
}
public void after(){
System.out.println("===============方法执行后=================");
}
}
<!-- 方式二: 自定义类 -->
<bean id="diy" class="com.hzx.diy.DiyPiontCut"></bean>
<aop:config>
<!-- 自定义切面 ref要引用的类 -->
<aop:aspect ref="diy">
<!-- 切入点 -->
<aop:pointcut id="point" expression="execution(* com.hzx.service.UserServiceImpl.*(..))"/>
<!-- 通知 -->
<aop:before method="before" pointcut-ref="point"></aop:before>
<aop:after method="after" pointcut-ref="point"></aop:after>
</aop:aspect>
</aop:config>
方式三:使用注解实现
@Aspect //标志这个类是一个切面
public class AnnotationPointCut {
@Before("execution(* com.hzx.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("============方法执行前===========");
}
@After("execution(* com.hzx.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("============方法执行后===========");
}
//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
@Around("execution(* com.hzx.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕前");
Signature signature = proceedingJoinPoint.getSignature();//获得前面
System.out.println("获得这个类的信息:"+signature);
//执行方法
Object proceed = proceedingJoinPoint.proceed();
System.out.println("环绕后");
}
}
<!-- 方式三:注解实现 -->
<bean id="annotationpointcut" class="com.hzx.diy.AnnotationPointCut"></bean>
<!--驱动开启支持 JDK(默认 proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy proxy-target-class="false"></aop:aspectj-autoproxy>
测试类:
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理 代理的是接口
UserService userService = (UserService)context.getBean("userService");
userService.add();
}
}
整合Mybatis
步骤:
- 导入相关jar包
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.13</version> </dependency> <!-- spring操作数据库 还需要一个Spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.13</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.8.RC1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> </dependencies>
- 编写配置文件
- 测试
回忆Mybatis
- 编写实体类
- 编写核心配置文件
- 编写接口
- 编写Mapper.xml
- 测试
Mybatis-Spring
1.编写数据源配置
2.sqlSessionFactory
3.sqlSessionTemplate
4.需要给接口加实现类
5.将自己写的实现类,注入到Spring中
6.测试
声明式事务
回顾事务
- 要么都成功,要么都失败
- 事务在项目开发中,十分重要,涉及到数据的一致性问题
- 确保完整性和一致性
事务ACID原则:
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作同一资源,防止数据损坏
- 持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中
spring中的事务管理
- 声明式事务:AOP
<!-- 结合AOP 实现事务的织入 --> <!-- 配置事务通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- 给那些方法配置事务 --> <!-- 配置事务的传播特性propagation: new --> <tx:attributes> <tx:method name="addUser" propagation="REQUIRED"/> <tx:method name="deleteUser"></tx:method> <tx:method name="*" propagation="REQUIRED"></tx:method> </tx:attributes> </tx:advice> <!-- 配置事务切入 --> <aop:config> <aop:pointcut id="txPointCut" expression="execution(* com.hzx.mapper.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"></aop:advisor> </aop:config>
- 编程式事务:需要在代码中,进行事务的管理
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致的情况下;
- 如果我们不在Spring中去配置声明式事务,我们就需要在代码中手动配置事务
- 事务在项目的开发中十分重要,涉及到数据的一致性和完整性问题
关注狂神说Java 有免费教学资源