拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 Spring中的宣告式事务管理

Spring中的宣告式事务管理

白鹭 - 2022-02-02 2207 0 0

Spring中的宣告式事务管理

1.创建一个测验类

package com.dzj.service;

import com.dzj.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
public class UserService {

    @Autowired
    UserDaoImpl userDao;

    public String addAndReduce(int account){
        try {
            userDao.add(account);
        	int i = 10/0;  //模拟例外
            userDao.reduce(account);
            return "成功了";
        }catch (Exception e){
            System.out.println("操作失败:"+e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();  //手动回滚
//            throw new RuntimeException("heihei");
            return "操作失败,有例外!";
        }

    }
}

2.撰写xml组态档 applicationbean.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 http://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 http://www.springframework.org/schema/aop/spring-aop.xsd">

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

    <!--资料池连接-->
    <bean id="dataSource"  destroy-method="close">
        <property name="url" value="https://www.cnblogs.com/aadzj/archive/2021/12/22/jdbc:mysql:///user_db"></property>
        <property name="username" value="https://www.cnblogs.com/aadzj/archive/2021/12/22/root"></property>
        <property name="password" value="https://www.cnblogs.com/aadzj/archive/2021/12/22/aadzj"></property>
        <property name="driverClassName" value="https://www.cnblogs.com/aadzj/archive/2021/12/22/com.mysql.jdbc.Driver"></property>
    </bean>

    <!--配置JdbcTemplate物件,注入dataSource-->
    <bean id="jdbcTemplate" >
        <!--注入资料源dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--创建事务管理器-->
    <bean id="transactionManager" >
        <!--注入资料源dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--组态档方式配置事务-->
    <!--配置通知-->
    <tx:advice id="txadvice">
        <!--配置事务自变量-->
        <tx:attributes>
            <!--指定哪种规则的方法上添加事务-->
            <tx:method name="addAndReduce" propagation="REQUIRED"/>
            <!--<tx:method name="addAnd*"/>-->
        </tx:attributes>
    </tx:advice>

    <!--配置切入点和切面-->
    <aop:config>
        <!--配置切入点-->
        <aop:pointcut id="pt" expression="execution(* com.dzj.service.UserService.*(..))"></aop:pointcut>
        <!--配置切面-->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt"></aop:advisor>
    </aop:config>

</beans>

3.测验方法

@Test
public void userTest1(){

    ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("applicationbean.xml");
    UserService userService = context.getBean("userService", UserService.class);
    System.out.println(userService.addAndReduce(100));
}

1.创建一个测验类

package com.dzj.service;

import com.dzj.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)  //事务注解,可以加在类上面,也可以加在方法上
public class UserService {

    @Autowired
    UserDaoImpl userDao;

    public String addAndReduce(int account){
        try {
            userDao.add(account);
            int i = 10/0;  //模拟例外
            userDao.reduce(account);
            return "成功了";
        }catch (Exception e){
            System.out.println("操作失败:"+e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();  //手动回滚
//            throw new RuntimeException("heihei");
            return "操作失败,有例外!";
        }

    }
}

2.撰写xml组态档 applicationbean2.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

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

    <!--资料池连接-->
    <bean id="dataSource"  destroy-method="close">
        <property name="url" value="https://www.cnblogs.com/aadzj/archive/2021/12/22/jdbc:mysql:///user_db"></property>
        <property name="username" value="https://www.cnblogs.com/aadzj/archive/2021/12/22/root"></property>
        <property name="password" value="https://www.cnblogs.com/aadzj/archive/2021/12/22/aadzj"></property>
        <property name="driverClassName" value="https://www.cnblogs.com/aadzj/archive/2021/12/22/com.mysql.jdbc.Driver"></property>
    </bean>

    <!--配置JdbcTemplate物件,注入dataSource-->
    <bean id="jdbcTemplate" >
        <!--注入资料源dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--创建事务管理器-->
    <bean id="transactionManager" >
        <!--注入资料源dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--开启事务注解 指定事务管理器-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

3.测验方法

@Test
public void userTest(){

    ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("applicationbean2.xml");
    UserService userService = context.getBean("userService", UserService.class);
    System.out.println(userService.addAndReduce(100));
}

1.创建一个配置类,替代xml组态档

package com.dzj.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration  //配置类
@ComponentScan(basePackages = "com.dzj")  //注解扫描
@EnableTransactionManagement //开启事务
public class TxConfig {

    //1.创建数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///user_db");
        dataSource.setUsername("root");
        dataSource.setPassword("aadzj");
        return dataSource;
    }

    //2.配置JdbcTemplate物件,注入dataSource
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){  //根据型别到ioc中找到DataSource
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //注入DataSource
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //3.创建事务管理器
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}

2.创建一个测验类

package com.dzj.service;

import com.dzj.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)  //事务注解,可以加在类上面,也可以加在方法上
public class UserService {

    @Autowired
    UserDaoImpl userDao;

    public String addAndReduce(int account){
        try {
            userDao.add(account);
            int i = 10/0;  //模拟例外
            userDao.reduce(account);
            return "成功了";
        }catch (Exception e){
            System.out.println("操作失败:"+e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();  //手动回滚
//            throw new RuntimeException("heihei");
            return "操作失败,有例外!";
        }

    }
}

3.测验方法

@Test
public void userTest3(){

    AnnotationConfigApplicationContext context =
            new AnnotationConfigApplicationContext(TxConfig.class);
    UserService userService = context.getBean("userService", UserService.class);
    System.out.println(userService.addAndReduce(100));
}

本文来自博客园,作者:小公羊,转载请注明原文链接:https://www.cnblogs.com/aadzj/p/15719776.html

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *