1.Spring

1.简介

Spring : 春天 --->给软件行业带来了春天

2002年,Rod Jahnson首次推出了Spring框架雏形interface21框架。

2004年3月24日,Spring框架以interface21框架为基础,经过重新设计,发布了1.0正式版。

很难想象Rod Johnson的学历 , 他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。

Spring理念 : 使现有技术更加实用 . 本身就是一个大杂烩 , 整合现有的框架技术

官网 : http://spring.io/

官方下载地址 : https://repo.spring.io/libs-release-local/org/springframework/spring/

GitHub : https://github.com/spring-projects

2.优点

1、Spring是一个开源免费的框架 , 容器 .

2、Spring是一个轻量级的框架 , 非侵入式的 .

3、控制反转 IoC , 面向切面 Aop

4、对事物的支持 , 对框架的支持

.......

一句话概括:

Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器(框架)。

3.组成

Spring 框架是一个分层架构,由 7 个定义良好的模块组成。Spring 模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式 .

组成 Spring 框架的每个模块(或组件)都可以单独存在,或者与其他一个或多个模块联合实现。每个模块的功能如下:

  • 核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory,它是工厂模式的实现。BeanFactory 使用控制反转(IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。
  • Spring 上下文:Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企业服务,例如 JNDI、EJB、电子邮件、国际化、校验和调度功能。
  • Spring AOP:通过配置管理特性,Spring AOP 模块直接将面向切面的编程功能 , 集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理任何支持 AOP的对象。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖组件,就可以将声明性事务管理集成到应用程序中。
  • Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构。
  • Spring ORM:Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构。
  • Spring Web 模块:Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。所以,Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
  • Spring MVC 框架:MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口,MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP、Velocity、Tiles、iText 和 POI。

4.拓展

Spring Boot与Spring Cloud

  • Spring Boot 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务;
  • Spring Cloud是基于Spring Boot实现的;
  • Spring Boot专注于快速、方便集成的单个微服务个体,Spring Cloud关注全局的服务治理框架;
  • Spring Boot使用了约束优于配置的理念,很多集成方案已经帮你选择好了,能不配置就不配置 , Spring Cloud很大的一部分是基于Spring Boot来实现,Spring Boot可以离开Spring Cloud独立使用开发项目,但是Spring Cloud离不开Spring Boot,属于依赖的关系。
  • SpringBoot在SpringClound中起到了承上启下的作用,如果你要学习SpringCloud必须要学习SpringBoot。

2.Spring—IOC

1.在Maven项目中添加Spring依赖

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.9</version>
    </dependency>
</dependencies>

2.IOC的本质

控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IOC的一种方法,在没有IoC的程序中,我们使用面向对象的编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

控制反转是通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。

3.配置Spring的元数据

<?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="hello" class="com.dzj.pojo.Hello">
       <property name="name" value="dengzhijiang"></property>
   </bean>
    <!-- more bean definitions go here -->
</beans>

4.获取Spring的上下文对象

读取容器

ApplicationContext context = new ClassPathXmlApplicationContext("benas.xml");

5.Spring创建对象

<bean id="userService" class="com.dzj.service.impl.UserServiceImpl">
    <!--
        ref:引用Spring容器中已经创建好的对象
        value:基本的值,基本数据类型
    -->
    <property name="userDao" ref="oracle"></property>
</bean>

6.不同数据类型的注入方式

	private String name;
    private Address address;
    private String[] books;
    private List<String> hobbies;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
<bean id="address" class="com.dzj.pojo.Address">
        <property name="address" value="湛江市"></property>
    </bean>
    <bean id="student" class="com.dzj.pojo.Student">
        <!--第一种,普通值注入,value-->

        <property name="name" value="邓志江" />
        <!--第二种,bean注入,ref-->
        <property name="address" ref="address"/>

        <!--数组-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <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="44088219981211"></entry>
                <entry key="银行卡" value="201824113212"></entry>
            </map>
        </property>
        <!--set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>
        <!--null-->
        <property name="wife">
            <null/>
        </property>
        <!--properties-->
        <property name="info">
            <props>
                <prop key="driver">20182411</prop>
                <prop key="gender">男</prop>
                <prop key="username">小明</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>

7.扩展方式注入

c命名空间和p命名空间的注入:不能直接使用,需要导入xml约束

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
<!--p命名空间注入,可以直接注入属性的值,property-->
<bean id="user" class="com.dzj.pojo.User" p:name="邓志江" p:age="22"></bean>
<!--c命名空间注入,通过构造器注入,construct-args-->
<bean id="user2" class="com.dzj.pojo.User" c:name="林勇" c:age="22" ></bean>

8.bean的作用域

1、单例模式(Spring默认模式)

<bean id="user" class="com.dzj.pojo.User" p:name="邓志江" p:age="22" scope="singleton"></bean>

2、原型模式(每次从容器中get的时候,都会产生一个新的对象!

<bean id="user2" class="com.dzj.pojo.User" c:name="林勇" c:age="22" scope="prototype"></bean>

3、其余的 @request、@sesstion、@application 这些只能在web开发中使用到!

9.bean的自动装配

  1. autowired:byName ---> 必须保证所有的 bean 的 id 的唯一,并且这个 bean 需要和自动注入的属性的 set 方法的值一致。
  2. autowired:byType ---> 必须保证所有的 bean 的 class 的唯一,并且这个 bean 需要和自动注入的属性的类型一致!
private String name;
@Autowired
private Cat cat;
@Autowired
private Dog dog;
<!--自动装配需要加上-->
<context:annotation-config/>
<bean id="cat" class="com.dzj.pojo.Cat"></bean>
<bean id="dog" class="com.dzj.pojo.Dog"></bean>
<!--
    byName: 会自动在容器的上下文中查找,和自己对象set方法后面值对应的 beanid!
    byType: 会自动在容器的上下文中查找,和自己对象属性类型相同的 bean!
-->
<bean id="person" class="com.dzj.pojo.Person" autowire="byName">
    <property name="name" value="小公羊"/>
    <!--<property name="cat" ref="cat"/>-->
    <!--<property name="dog" ref="dog"/>-->
</bean>

注解说明

-@autowired:自动装配通过类型、名字

​ 如果@autowired没有自动装配上属性,则需要通过@qualifier(value = “ ”)

-@nullable 如果字段标记了这个注解,说明这个字段可以为null

-@resource:自动装配通过类型、名字

将类注册到容器中

-@component :组件,放在这个类上,说明这个类被Spring管理了,就是bean!

​ 等价于:

-@Value: 给属性赋值,等价于:

<!--需要在 xml 中开启注解扫描,才能检测到注册bean的类-->
<context:component-scan base-package="com.dzj.dao"/>

@component组件的衍生:在web开发中,会按照三层架构分层

dao【@Repository】

service【@Service】

controller【@Controller】

这四个注解功能都是一样的,都是将我们的类注册到Spring容器

10.在纯java类中配置的方法

第一种方法:

1、在实体类的头部添加注解--@component

@Value注解用来给对象的属性赋值

@Component
public class User {
    @Value("zhijiang")
    public String name;

    public void show(){
        System.out.println("成功了...");
    }
}

2、在配置类 MyConfig 中添加两个注解

--@configuration ---> 代替 beans.xml 文件,相当于这个类就是一个spring容器

--@componentScan --> 用来扫描实体类,哪些类注册了 bean

@Configuration
@ComponentScan("com.dzj.pojo")
public class MyConfig {

}

3、获取容器中的对象

ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("user", User.class);

第二种方法:

1、无需在实体类中添加多余的注解,若想给对象的属性赋值,只需用@Value注解给属性赋值即可

public class User {
    @Value("zhijiang")
    public String name;
    public void show(){
        System.out.println("成功了...");
    }
}

2、只需在配置类中添加一个返回对象的方法,并且在该方法上方添加一个注解@bean

public class MyConfig {
    @Bean
    public User getUser(){
        return new User();
    }
}

@bean就是beans.xml文档中的

方法名:getUser就是标签中的 id

new user():就是就是标签中的class

3、获取容器中的对象

ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("getUser", User.class);

3.Spring—AOP

1.聊聊AOP

2.动态代理

2.1.被代理的接口
public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();
}
2.2.接口的实现类(真实角色)
public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("添加了一个用户");
    }

    public void delete() {
        System.out.println("删除了一个用户");
    }

    public void update() {
        System.out.println("修改了一个用户");
    }

    public void query() {
        System.out.println("查询了一个用户");
    }
}
2.3.自动生成代理类的中间类
//等会我们用这个类,自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的接口
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

    //生成得到代理类
    public Object getProxy(){
        return  Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }

    //处理代理实例,并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        PrintLog(method.getName());
        Object result = method.invoke(target,args);
        fee();
        return result;
    }

    public void PrintLog(String msg){
        System.out.println("[debug]执行了"+msg+"方法!");
    }
    public void fee(){
        System.out.println("收中介费");
    }

}
2.4.执行类
public static void main(String[] args) {

    //真实角色
    UserServiceImpl userService = new UserServiceImpl();

    //代理角色,不存在,从ProxyInvocationHandler类中动态生成
    ProxyInvocationHandler pih = new ProxyInvocationHandler();
    //在 ProxyInvocationHandler 类中通过setTarget()方法得到要被代理的真是角色 userService
    pih.setTarget(userService);
    // 获取代理角色
    UserService proxy = (UserService) pih.getProxy();
    proxy.add();  //执行代理实例,以及一些附属的操作
}

3.在Spring中实现AOP

1.使用原生态 API接口

使用原生态 API接口**(主要是SpringAPI接口实现)

1. 创建接口,包含真实角色要实现的抽象方法
public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();
}
2. 实现接口的类(真实角色)
public class UserServiceImpl implements UserService {

    public void add() {
        System.out.println("添加了一个用户!");
    }

    public void delete() {
        System.out.println("删除了一个用户!");
    }

    public void update() {
        System.out.println("修改了一个用户!");
    }

    public void query() {
        System.out.println("查询了一个用户!");
    }
}
3. 执行环绕增强的类
public class Log implements MethodBeforeAdvice {

    //method:要执行的目标对象的方法
    //args:参数
    //target:目标对象
    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:返回值
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {

        System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
    }
}
4. 创建并配置applicationContext.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">    
    <!--注册bean-->    
    <bean id="userService" class="com.dzj.service.UserServiceImpl"/>    
    <bean id="log" class="com.dzj.log.Log"/>    
    <bean id="afterLog" class="com.dzj.log.AfterLog"/>    
    <!--方式一:使用原生态 API接口-->    
    <!--配置aop:需要导入aop的约束-->    
    <aop:config>        
        <!--创建切入点:expression:表达式,excution(要执行的位置!* * * * *)-->        
        <aop:pointcut id="pointcut" expression="execution(* com.dzj.service.UserServiceImpl.*(..))" />        		  <!--执行环绕增强,把增强引入切入点-->        
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>        
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>    
    </aop:config>
</beans>
5. 添加测试类
public class MyTest {    
    public static void main(String[] args) {        
    	ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");       
    	//动态代理的是接口,而不是接口的实现类        
    	UserService userService = context.getBean("userService", UserService.class);
        userService.query();    
    }
}

2.自定义类(主要是切面定义)

1. 创建被代理的接口
public interface UserService {    
    public void add();    
    public void delete();    
    public void update();    
    public void query();
}
2. 实现被代理接口的类(真实角色)
public class UserServiceImpl implements UserService {    
    public void add() {        
        System.out.println("添加了一个用户!");    
    }    
    public void delete() {        
        System.out.println("删除了一个用户!");    
    }    
    public void update() {        
        System.out.println("修改了一个用户!");    
    }    
    public void query() {        
        System.out.println("查询了一个用户!");    
    }
}
3. 自定义类
public class diy {    
    public void before(){        
        System.out.println("*****方法执行前*****");    
    }    
    public void after(){        
        System.out.println("*****方法执行后*****");    
    }
}
4. applicationContext.xml 配置文件
<!--注册bean-->
<bean id="userService" class="com.dzj.service.UserServiceImpl"/>
<bean id="log" class="com.dzj.log.Log"/>
<bean id="afterLog" class="com.dzj.log.AfterLog"/>
<!--方式二:自定义类-->
<bean id="diy" class="com.dzj.customize.diy"/>
<aop:config>    
    <!--自定义切面,ref 要引用的类-->    
    <aop:aspect ref="diy">        
        <!--切入点-->        
        <aop:pointcut id="point" expression="execution(* com.dzj.service.UserServiceImpl.*(..))"/>
        <!--通知-->        
        <aop:before method="before" pointcut-ref="point"/>        
        <aop:after method="after" pointcut-ref="point"/>    
    </aop:aspect>
</aop:config>
5. 测试类
public class MyTest {    
    public static void main(String[] args) {        
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理的是接口,而不是接口的实现类       
        UserService userService = context.getBean("userService", UserService.class);
        userService.query();    
    }
}

3.使用注解

1. 创建一个类,通过 @Aspect 注解的方式标注为此类为一个切面
@Aspect  //标注这个类是一个切面
public class AnnotationPointCut {    
    @Before("execution(* com.dzj.service.UserServiceImpl.*(..))")    
    public void before(){        
        System.out.println("*****方法执行前*****");    
    }    
    @After("execution(* com.dzj.service.UserServiceImpl.*(..))")    
    public void after(){        
        System.out.println("*****方法执行后*****");    
    }    
    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点    
    @Around("execution(* com.dzj.service.UserServiceImpl.*(..))")    
    public void around(ProceedingJoinPoint jp) throws Throwable {        
        System.out.println("环绕前");        
        Signature signature = jp.getSignature();//获得签名        
        System.out.println("signature:"+signature);        
        Object proceed = jp.proceed();//执行方法        
        System.out.println("环绕后");     
    }
}
2. applicationContext.xml配置文件
<!--方式三-->
<!--创建切入点-->
<bean id="annotationPointCut" class="com.dzj.customize.AnnotationPointCut"/>
<!--开启注解支持--><aop:aspectj-autoproxy/>
3. 被代理的接口、实现类、测试类均不变

4、AOP在Spring中的作用

提供声明式事务,允许用户自定义切面

(1)横切切入点:跨越应用程序多个模块的功能和方法。即是,与我们逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志、安全、缓存、事务等等......

(2)切面(ASPECT):横切关注点 被模块化的特殊对象。即,它是一个类。

(3)通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。

(4)目标(Tatget):被通知的对象。

(5)代理(Proxy):向目标对象应用通知之后创建的对象。

(6)切入点(PointCut):切面通知 执行的 “地点” 的定义。

(7)连接点(JoinPoint):与切入点匹配的执行点。

4.Spring-Mybatis

1. 回忆Mybatis

1. 新建一个实体类
@Data
public class User {
    private int uid;
    private String username;
    private String password;
}
2. 编写Mybatis核心配置文件
<?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.dzj.pojo"/>
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <!-- 将mapper文件加入到配置文件中,注册接口 -->
    <mappers>
        <mapper class="com.dzj.mapper.UserMapper"></mapper>
    </mappers>
</configuration>
3. 编写接口
public interface UserMapper {

    public List<User> selectUser();

}
4. 编写接口对应的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.dzj.mapper.UserMapper">
    <select id="selectUser" resultType="user">
        select * from test.user;
    </select>
</mapper>
5. 编写测试类
public class MyTest {

    @Test
    public void test() throws IOException {
        String resources = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resources);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = sessionFactory.openSession(true);

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userlist = mapper.selectUser();
        for(User user:userlist){
            System.out.println(user);
        }
    }
}

2. Mybatis-Spring

1. 编写数据源配置
<!--DataSource使用Spring的数据源替换Mybatis的配置  c3p0、dbcp、druid也可以
    我们这里使用Spring提供的JDBC : org.springframework.jdbc.datasource
-->
<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/test"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
</bean>
2. sqlSessionFactory
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!--绑定Mybati配置文件-->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:com/dzj/mapper/*.xml"/>
</bean>
3. sqlSessionTemplate
<!--SqlSessionTemplate:就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <!--只能使用构造器注入SQLSessionFactory,因为它没有set方法-->
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
4. 需要给接口加实现类
public class UserMapperImpl implements UserMapper {    
    //我们所有的操作,都是用sqlSession来执行,在原来,现在都使用SqlSessionTemplate    
    private SqlSessionTemplate sqlSession;    
    public void setSqlSession(SqlSessionTemplate sqlSession) {        
        this.sqlSession = sqlSession;    
    }    
    public List<User> selectUser() {       
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);       
        return mapper.selectUser(); 
    }
}
5. 将自己写的实现类,注入到Spring中
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.dzj.mapper.UserMapperImpl">    
    <property name="sqlSession" ref="sqlSession"/>
</bean>
6. 测试
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for(User user:userMapper.selectUser()){    
    System.out.println(user);
}

5.声明式事务

1. 事务的特点

  • 把一组业务当成一个业务来做,要么都成功要么都失败。
  • 事务在项目开发中,十分的重要,涉及到数据的一致性问题,不能马虎。
  • 确保一致性和完整性

事务ACID原则:

  • 原子性
  • 一致性
  • 隔离性
    • 多个业务可能同时操作同一个资源,防止数据损坏。
  • 持久性
    • 事务一旦被提交,无论系统发生什么问题,结果都不会被影响,被持久化的写到存储器中。

2. 事务的配置

	<!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--结合AOP实现事务的织入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些事务配置方法-->
        <!--配置事务的传播特性:new propagation-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
            <!--"name*" 代表所有方法-->
        </tx:attributes>
    </tx:advice>

    <!--配置事务的切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.dzj.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>	

3. spring中的事务管理

Spring在不同的事务管理API之上定义了一个抽象层,使得开发人员不必了解底层的事务管理API就可以使用Spring的事务管理机制。Spring支持编程式事务管理和声明式的事务管理。

编程式事务管理

  • 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
  • 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码

声明式事务管理

  • 一般情况下比编程式事务好用。
  • 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
  • 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。

使用Spring管理事务,注意头文件的约束导入 : tx

xmlns:tx="http://www.springframework.org/schema/tx"

http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

事务管理器

  • 无论使用Spring的哪种事务管理策略(编程式或者声明式)事务管理器都是必须的。
  • 就是 Spring的核心事务管理抽象,管理封装了一组独立于技术的方法。

JDBC事务

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <property name="dataSource" ref="dataSource" />
</bean>

配置好事务管理器后我们需要去配置事务的通知

<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
   <tx:attributes>
       <!--配置哪些方法使用什么样的事务,配置事务的传播特性-->
       <tx:method name="add" propagation="REQUIRED"/>
       <tx:method name="delete" propagation="REQUIRED"/>
       <tx:method name="update" propagation="REQUIRED"/>
       <tx:method name="search*" propagation="REQUIRED"/>
       <tx:method name="get" read-only="true"/>
       <tx:method name="*" propagation="REQUIRED"/>
   </tx:attributes>
</tx:advice>

spring事务传播特性:

事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。spring支持7种事务传播行为:

  • propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
  • propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
  • propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
  • propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
  • propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
  • propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
  • propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作

Spring 默认的事务传播行为是 PROPAGATION_REQUIRED,它适合于绝大多数的情况。

假设 ServiveX#methodX() 都工作在事务环境下(即都被 Spring 事务增强了),假设程序中存在如下的调用链:Service1#method1()->Service2#method2()->Service3#method3(),那么这 3 个服务类的 3 个方法通过 Spring 的事务传播机制都工作在同一个事务中。

就好比,我们刚才的几个方法存在调用,所以会被放在一组事务当中!

配置AOP

导入aop的头文件!

<!--配置aop织入事务-->
<aop:config>
   <aop:pointcut id="txPointcut" expression="execution(* com.kuang.dao.*.*(..))"/>
   <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>

进行测试

删掉刚才插入的数据,再次测试!

@Test
public void test2(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   UserMapper mapper = (UserMapper) context.getBean("userDao");
   List<User> user = mapper.selectUser();
   System.out.println(user);
}

思考问题?

为什么需要配置事务?

  • 如果不配置,就需要我们手动提交控制事务;
  • 事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!
内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/aadzj/p/15312220.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!