首页 > 其他分享 >Spring框架声明是事务

Spring框架声明是事务

时间:2024-06-20 17:00:53浏览次数:13  
标签:事务 String 框架 Spring Account act import actno public

声明式事务(Declarative Transaction Management)是Spring框架提供的一种对程序事务进行管理的方式。这种管理方式的核心思想是采用声明的方式(通常是在配置文件中声明,而非在代码中硬编码)来处理事务,从而简化开发过程,降低开发者处理复杂事务的难度。
在声明式事务中,开发者通过注解(如@Transactional)或基于配置的XML来管理事务,而不需要依赖底层API进行硬编码。这使得业务逻辑对象无需意识到它们正处于事务管理之中,因为事务管理属于系统层面的服务,而不是业务逻辑的一部分。因此,当需要改变事务管理策略时,只需在配置文件中重新配置即可,无需修改代码并重新编译,从而大大提高了维护的便利性。

转账案例
  • dao接口
package com.powernode.bank.dao;


import com.powernode.bank.pojo.Account;

public interface AccountDao {
    //根据账号查询账户信息
    Account selectByActno(String actno);

    //更新账户信息
    int update(Account act);

    //保存账户信息
    int insert(Account act);
}
  • dao实现接口
package com.powernode.bank.dao.impl;

import com.powernode.bank.dao.AccountDao;
import com.powernode.bank.pojo.Account;
import jakarta.annotation.Resource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class AccountDaoImpl implements AccountDao {

    @Resource
    private JdbcTemplate jdbcTemplate;


    @Override
    public Account selectByActno(String actno) {
        String sql = "select actno,balance from t_act where actno = ?";
        Account account = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Account.class), actno);
        System.out.println("笑"+account);
        return account;
    }

    @Override
    public int update(Account act) {
        String sql = "update t_act set balance = ? where actno = ?";
        int update = jdbcTemplate.update(sql, act.getBalance(), act.getActno());
        return update;
    }

    @Override
    public int insert(Account act) {
        String sql = "insert into t_act values(?,?)";
        return jdbcTemplate.update(sql,act.getActno(),act.getBalance());
    }
}
  • pojo实体类
package com.powernode.bank.pojo;

public class Account {
    private String actno;
    private Double balance;

    public Account() {
    }

    public Account(String actno, Double balance) {
        this.actno = actno;
        this.balance = balance;
    }

    public String getActno() {
        return actno;
    }

    public void setActno(String actno) {
        this.actno = actno;
    }

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "actno='" + actno + '\'' +
                ", balance=" + balance +
                '}';
    }
}
  • service接口
package com.powernode.bank.service;

public interface AccountService {
    void transfer(String fromActno, String toActno, double money);
}
  • service实现类
package com.powernode.bank.service.impl;

import com.powernode.bank.dao.AccountDao;
import com.powernode.bank.pojo.Account;
import com.powernode.bank.service.AccountService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountDao accountDao;

    //控制事务
    @Override
    public void transfer(String fromActno, String toActno, double money) {
        //查询余额
        Account fromAct = accountDao.selectByActno(fromActno);
        if (fromAct.getBalance() < money){
            throw new RuntimeException("余额不足!!");
        }
        //余额充足
        Account toAct = accountDao.selectByActno(toActno);

        //将内存中两个对象的余额先修改
        fromAct.setBalance(fromAct.getBalance() - money);
        toAct.setBalance(toAct.getBalance() + money);

        //数据库更新
        int count = accountDao.update(fromAct);

        //模拟异常
       /* String s = null;
        s.toString();*/

        count += accountDao.update(toAct);



        if (count !=2){
            throw new RuntimeException("转账失败,联系银行");
        }
    }

}
  • spring.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" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--组件扫描-->
    <context:component-scan base-package="com.powernode.bank"/>

    <!--配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://192.168.1.41:3306/test"/>
        <property name="username" value="root"/>
        <property name="password" value="Abc123***"/>
    </bean>

    <!--配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--配置事务管理器-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--开启事务注解驱动器-->
<!--    <tx:annotation-driven  transaction-manager="dataSourceTransactionManager"/>-->

    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
        <!--配置通知的transfer方法-->
        <tx:attributes>
            <tx:method name="transfer" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
        </tx:attributes>
    </tx:advice>

    <!--配置切面-->
    <aop:config>
        <!--切点-->
        <aop:pointcut id="txPointcut" expression="execution(* com.powernode.bank.service..*(..))"/>
        <!--切面 = 事务通知+切点-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>

</beans>
  • 测试
    @Test
    public void testNoAnnotation() {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring.xml");
        AccountService accountServiceImpl = classPathXmlApplicationContext.getBean("accountServiceImpl", AccountService.class);
        try {
            accountServiceImpl.transfer("act-001", "act-002", 10000);
            System.out.println("转账成功");
        } catch (Exception e){
            e.printStackTrace();
        }
    }

数据库截图

标签:事务,String,框架,Spring,Account,act,import,actno,public
From: https://www.cnblogs.com/DuWenjie/p/18259001

相关文章

  • 黑马程序员2024最新SpringCloud微服务开发与实战 个人学习心得、踩坑、与bug记录Day3
    你好,我是Qiuner.为帮助别人少走弯路和记录自己编程学习过程而写博客这是我的githubhttps://github.com/Qiuner⭐️giteehttps://gitee.com/Qiuner......
  • 凤凰架构记02-事务
    事务的基本特性A原子性:一系列操作为一个原子,都成功或都撤销I隔离性:不同操作之间读写数据相互独立,不会彼此影响D持久性:成功提交的数据都会被持久化,不会丢失C一致性:一致性为最终目的,所有事物处理最终的数据状态保持一致 内部一致性:单数据源有确定并发事务的读写顺序外部一致......
  • RTX5全家桶源码综合模板发布,含FreeRTOS内核版本,将其打造成直接面向实际项目应用的综合
    【说明】1、RTX5全家桶的优势就是简单易用,初学的话,上手很快,稳定性也是杠杠的,且容易做稳定。2、同时RTX5也是有汽车级,工业级,医疗和铁路安全认证,只是安全级别比ThreadX要稍微低些。3、当前RTX5中间件源码已经开源了,大大方便大家问题的排查。同时提供了FreeRTOS内核版本,方便大家选......
  • Spring Cloud Gateway网关下Knife4j文档聚合,以及动态路由的读取和代码配置
    SpringCloudGateway网关下Knife4j文档聚合,以及动态路由的读取和配置一.Knife4j文档聚合1.1基础环境明细1.2集成knife4j1.2.1maven1.2.2yml配置1.2.2.1其他模块配置1.2.2.2manual手动配置模式1.2.2.3discover服务发现模式1.2.2.3==这里请注意==:如果你使用了:S......
  • SpringBoot开发中的日志级别
    文章目录前言一、日志级别是什么?二、使用步骤1.**添加依赖**:2.**配置日志级别**:3.**在代码中使用日志**:总结前言在SpringBoot开发中,日志系统是一个不可或缺的部分,它帮助我们跟踪应用程序的运行状态、调试代码以及监控性能。然而,随着日志信息的不断增加,如何合......
  • springboot——https请求异常Invalid character found in method name. HTTP method n
    遇到问题的情况接口没有配置https,请求时用https会此异常。其他情况1、问题现象java.lang.IllegalArgumentException:Invalidcharacterfoundinmethodname.HTTPmethodnamesmustbetokensatorg.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11Inp......
  • 任务调度框架革新:TASKCTL在Docker环境中的高级应用
    Docker:轻量级容器化技术的魅力Docker作为一款开源的轻量级容器化技术,近年来在IT界掀起了一股热潮。它通过封装应用及其运行环境,使得开发者可以快速构建、部署和运行应用。Docker的优势在于其轻量级、可移植性和可扩展性,它使得应用部署变得更加简单、快捷。TASKCTL:自动化运......
  • 使用Spring的StopWatch类优雅打印方法执行耗时
    在做开发的时需要统计每个方法的执行消耗时间,或者记录一段代码执行时间,最简单的方法就是打印当前时间与执行完时间的差值,然后这样如果执行大量测试的话就很麻烦,并且不直观,然而使用使用Spring的StopWatch类就可以优雅打印方法执行耗时间简单的Demoimportorg.springframework......
  • Spring5中常用的注解说明
    用于创建对象的注解相当于:<beanid=""class="">1.1@Component注解作用:把资源让 spring 来管理。相当于在 xml 中配置一个 bean。属性:value:指定bean的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名。首字母小写。1.2@Controller @Servic......
  • 【毕业设计】基于Springboot的酒店管理系统的设计与实现
    1.项目概述随着社会经济不断的发展,很多行业都发生了很大的变化,各种管理系统层出不穷,关于酒店管理系统也是其中的一种。近几年来,随着各行各业计算机智能化管理的转型,以及人们经济实力的提升,人们对于酒店住宿的需求不断的提升,用户的增多导致酒店管理信息的不断增多,于是酒店管理......