130.【Spring注解_AOP】(二)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 130.【Spring注解_AOP】

(三)、声明式事务

1.声明式事务 - 环境搭建

(1).导入依赖
<!--    Spring包  ->IOC  -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>
                <!--     C3P0数据包 ->数据源  -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!--    Spring切面的包   ->aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>
        <!--    Spring-JDBC -> jdbcTemplate   -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>
(2).实体类和业务层

1.实体类

package com.jsxs.bean;
/**
 * @Author Jsxs
 * @Date 2023/8/22 14:27
 * @PackageName:com.jsxs.bean
 * @ClassName: Admin
 * @Description: TODO
 * @Version 1.0
 */
public class Admin {
    private int id;
    private String name;
    private String password;
    public Admin() {
    }
    public Admin(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "Admin{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

2.Dao层:

package com.jsxs.mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
/**
 * @Author Jsxs
 * @Date 2023/8/22 14:28
 * @PackageName:com.jsxs.mapper
 * @ClassName: AdminMapper
 * @Description: TODO
 * @Version 1.0
 */
@Repository
public class AdminMapper {
    @Resource
    private JdbcTemplate jdbcTemplate;
    public void add(){
        String sql="insert into admin(name,password) values(?,?)";
        int i = jdbcTemplate.update(sql,222,222);  // 后面的是参数也就是占位符,占位符有几个,参数也就有几个
        if (i>0){
            System.out.println("添加数据成功!!");
        }else {
            System.out.println("添加数据失败!!");
        }
    }
}

3.业务层

package com.jsxs.service;
import com.jsxs.mapper.AdminMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
 * @Author Jsxs
 * @Date 2023/8/22 14:30
 * @PackageName:com.jsxs.service
 * @ClassName: AdminServer
 * @Description: TODO
 * @Version 1.0
 */
@Service
public class AdminServer {
    @Resource
    AdminMapper adminMapper;
    public void insert(){
        adminMapper.add();
    }
}

4.配置类

package com.jsxs.tx;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
 * @Author Jsxs
 * @Date 2023/8/22 14:06
 * @PackageName:com.jsxs.tx
 * @ClassName: TxConfig
 * @Description: TODO  声明式事务
 * 1. 导入相关依赖 : 数据源、数据库驱动、Spring-JDBC->(提供了JDBCTemplate)
 * 2.配置数据源,JDBCTemplate(Spring提供的简化数据库操作的工具)操作数据库
 * @Version 1.0
 */
@Configuration
@ComponentScan(value = "com.jsxs")
@PropertySource(value = "classpath:db.properties")
public class TxConfig {
    // 1.配置我们的数据源
    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        // 1.1.c3p0数据源
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/demo1");
        dataSource.setUser("root");
        dataSource.setPassword("121788");
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        return dataSource;
    }
    // 2.我们设置JDBC的模板,又因为这个模板需要数据源,所以我们要存放我们的数据源。又因为在配置类中的参数是先从IOC容器中拿取的,所以我们直接设置成参数即可。
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}

5.测试

package com.jsxs.Test;
import com.jsxs.service.AdminServer;
import com.jsxs.tx.TxConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
 * @Author Jsxs
 * @Date 2023/8/22 14:45
 * @PackageName:com.jsxs.Test
 * @ClassName: AOP_TX
 * @Description: TODO
 * @Version 1.0
 */
public class AOP_TX {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TxConfig.class);
        for (String beanDefinitionName : applicationContext.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }
        AdminServer server = applicationContext.getBean(AdminServer.class);
        server.insert();
    }
}

2.声明式事务 - 测试成功

(1).遇见问题
*                      1. 导入相关依赖 : 数据源、数据库驱动、Spring-JDBC->(提供了JDBCTemplate)
 *                      2.配置数据源,JDBCTemplate(Spring提供的简化数据库操作的工具)操作数据库
 *                 ⭐     3.给方法上标注@Transactional 表示当前方法是一个事务方法.
 *                 ⭐    4.@EnableTransactionManagement 需要放在配置类进行开启注解的事务
 *                 ⭐     5.添加PlatformTransactionManager这个组件

我们在插入的方法中故意设置一个异常的操作,然后我们执行这个方法但是我们发现我们并不会发生事务回滚(即 失败都失败,成功都成功!);

(2).解决问题 -> 事务型(成功全成功_失败全失败)
package com.jsxs.service;
import com.jsxs.mapper.AdminMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
 * @Author Jsxs
 * @Date 2023/8/22 14:30
 * @PackageName:com.jsxs.service
 * @ClassName: AdminServer
 * @Description: TODO
 * @Version 1.0
 */
@Service
public class AdminServer {
    @Resource
    AdminMapper adminMapper;
    @Transactional  // 声明标注事务的注解⭐
    public void insert(){
        adminMapper.add();
        // 2.故意制造异常 ⭐⭐
        System.out.println(1/0);
    }
}
  1. 基于XML文件的

  1. 基于注解

1.业务层添加上事务注解

package com.jsxs.service;
import com.jsxs.mapper.AdminMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
 * @Author Jsxs
 * @Date 2023/8/22 14:30
 * @PackageName:com.jsxs.service
 * @ClassName: AdminServer
 * @Description: TODO
 * @Version 1.0
 */
@Service
public class AdminServer {
    @Resource
    AdminMapper adminMapper;
    @Transactional
    public void insert(){
        adminMapper.add();
        System.out.println(1/0);
    }
}

2.需要在配置类上开启注解支持

package com.jsxs.tx;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
 * @Author Jsxs
 * @Date 2023/8/22 14:06
 * @PackageName:com.jsxs.tx
 * @ClassName: TxConfig
 * @Description: TODO  声明式事务
 *                      1. 导入相关依赖 : 数据源、数据库驱动、Spring-JDBC->(提供了JDBCTemplate)
 *                      2.配置数据源,JDBCTemplate(Spring提供的简化数据库操作的工具)操作数据库
 *                      3.给方法上标注@Transactional 表示当前方法是一个事务方法.
 *                      4.@EnableTransactionManagement 需要放在配置类进行开启注解的事务
 * @Version 1.0
 */
@Configuration
@ComponentScan(value = "com.jsxs")
@PropertySource(value = "classpath:db.properties")
@EnableTransactionManagement  ⭐
public class TxConfig {
    // 1.配置我们的数据源
    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        // 1.1.c3p0数据源
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/demo1");
        dataSource.setUser("root");
        dataSource.setPassword("121788");
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        return dataSource;
    }
    // 2.我们设置JDBC的模板,又因为这个模板需要数据源,所以我们要存放我们的数据源。又因为在配置类中的参数是先从IOC容器中拿取的,所以我们直接设置成参数即可。
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}

3.进行测试的操作

package com.jsxs.Test;
import com.jsxs.service.AdminServer;
import com.jsxs.tx.TxConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
 * @Author Jsxs
 * @Date 2023/8/22 14:45
 * @PackageName:com.jsxs.Test
 * @ClassName: AOP_TX
 * @Description: TODO
 * @Version 1.0
 */
public class AOP_TX {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TxConfig.class);
        for (String beanDefinitionName : applicationContext.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }
        AdminServer server = applicationContext.getBean(AdminServer.class);
        server.insert();
    }
}

4.结果我们发现缺少一个组件 PlatformTransactionManager

5. 给IOC容器中添加这个组件

package com.jsxs.tx;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jca.cci.connection.CciLocalTransactionManager;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
 * @Author Jsxs
 * @Date 2023/8/22 14:06
 * @PackageName:com.jsxs.tx
 * @ClassName: TxConfig
 * @Description: TODO  声明式事务
 *                      1. 导入相关依赖 : 数据源、数据库驱动、Spring-JDBC->(提供了JDBCTemplate)
 *                      2.配置数据源,JDBCTemplate(Spring提供的简化数据库操作的工具)操作数据库
 *                      3.给方法上标注@Transactional 表示当前方法是一个事务方法.
 *                      4.@EnableTransactionManagement 需要放在配置类进行开启注解的事务
 *                      5.添加PlatformTransactionManager这个组件
 * @Version 1.0
 */
@Configuration
@ComponentScan(value = "com.jsxs")
@PropertySource(value = "classpath:db.properties")
@EnableTransactionManagement  // ⭐
public class TxConfig {
    // 1.配置我们的数据源
    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        // 1.1.c3p0数据源
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/demo1");
        dataSource.setUser("root");
        dataSource.setPassword("121788");
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        return dataSource;
    }
    // 2.我们设置JDBC的模板,又因为这个模板需要数据源,所以我们要存放我们的数据源。又因为在配置类中的参数是先从IOC容器中拿取的,所以我们直接设置成参数即可。
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
    @Bean  // 在配置类中的@Bean注解的方法参数,参数默认是从IOC容器中赋值的 ⭐⭐
    public PlatformTransactionManager platformTransactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}

3.声明式事务原理

*   2.事务原理
 *                      (1).@EnableTransactionManagement
 *                              利用 TransactionManagementConfigurationSelector 给容器中会导入批量组件
 *                              导入两个组件
 *                                  (1).AutoProxyRegistrar (2).ProxyTransactionManagementConfiguration
 *                      (2).细聊 AutoProxyRegistrar
 *                              给容器中注入一个组件,利用后置处理器机制在对象创建以后,包装对象,返回一个代理对象(增强器),代理方法执行方法利用拦截器链进行调用
 *
 *                      (3).细聊 ProxyTransactionManagementConfiguration
 *                              1.给事务注册一个事务增强器->事务增强器要用事务注解的信息
 *                              2.事务拦截器
 *                                  (1).先获取事务相关的属性
 *                                  (2).在获取PlatformTransactionManager,如果事务先没有添加指定任何
 *                                      最终会从容器中按照类型获取一个PlateFormTransactionManager;
 *                                  (3).执行目标方法
 *                                      如果异常,获取到事务管理器,利用事务管理回滚操作
 *                                      如果正常,利用事务管理器,提交事务控制

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
打赏
0
0
0
0
15
分享
相关文章
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
32 0
|
17天前
|
微服务——SpringBoot使用归纳——Spring Boot中的切面AOP处理——Spring Boot 中的 AOP 处理
本文详细讲解了Spring Boot中的AOP(面向切面编程)处理方法。首先介绍如何引入AOP依赖,通过添加`spring-boot-starter-aop`实现。接着阐述了如何定义和实现AOP切面,包括常用注解如`@Aspect`、`@Pointcut`、`@Before`、`@After`、`@AfterReturning`和`@AfterThrowing`的使用场景与示例代码。通过这些注解,可以分别在方法执行前、后、返回时或抛出异常时插入自定义逻辑,从而实现功能增强或日志记录等操作。最后总结了AOP在实际项目中的重要作用,并提供了课程源码下载链接供进一步学习。
37 0
微服务——SpringBoot使用归纳——Spring Boot中的切面AOP处理——什么是AOP
本文介绍了Spring Boot中的切面AOP处理。AOP(Aspect Oriented Programming)即面向切面编程,其核心思想是分离关注点。通过AOP,程序可以将与业务逻辑无关的代码(如日志记录、事务管理等)从主要逻辑中抽离,交由专门的“仆人”处理,从而让开发者专注于核心任务。这种机制实现了模块间的灵活组合,使程序结构更加可配置、可扩展。文中以生活化比喻生动阐释了AOP的工作原理及其优势。
32 0
Spring Boot的核心注解是哪个?他由哪几个注解组成的?
Spring Boot的核心注解是@SpringBootApplication , 他由几个注解组成 : ● @SpringBootConfiguration: 组合了- @Configuration注解,实现配置文件的功能; ● @EnableAutoConfiguration:打开自动配置的功能,也可以关闭某个自动配置的选项 ● @ComponentScan:Spring组件扫描
Spring MVC常用的注解
@RequestMapping:用于处理请求 url 映射的注解,可用于类或方法上。用于类上,则表示类中 的所有响应请求的方法都是以该地址作为父路径。 @RequestBody:注解实现接收http请求的json数据,将json转换为java对象。 @ResponseBody:注解实现将conreoller方法返回对象转化为json对象响应给客户。 @Controller:控制器的注解,表示是表现层,不能用用别的注解代替 @RestController : 组合注解 @Conntroller + @ResponseBody @GetMapping , @PostMapping , @Put
SpringBoot+@Async注解一起用,速度提升
本文介绍了异步调用在高并发Web应用性能优化中的重要性,对比了同步与异步调用的区别。同步调用按顺序执行,每一步需等待上一步完成;而异步调用无需等待,可提升效率。通过Spring Boot示例,使用@Async注解实现异步任务,并借助Future对象处理异步回调,有效减少程序运行时间。
|
2月前
|
SpringBoot:SpringBoot通过注解监测Controller接口
本文详细介绍了如何通过Spring Boot注解监测Controller接口,包括自定义注解、AOP切面的创建和使用以及具体的示例代码。通过这种方式,可以方便地在Controller方法执行前后添加日志记录、性能监控和异常处理逻辑,而无需修改方法本身的代码。这种方法不仅提高了代码的可维护性,还增强了系统的监控能力。希望本文能帮助您更好地理解和应用Spring Boot中的注解监测技术。
77 16
Spring AOP—通知类型 和 切入点表达式 万字详解(通俗易懂)
Spring 第五节 AOP——切入点表达式 万字详解!
147 25
|
2月前
|
Spring AOP—深入动态代理 万字详解(通俗易懂)
Spring 第四节 AOP——动态代理 万字详解!
100 24
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
178 26