手写 spring 事务框架-注解版,基于aop+反射+自定义注解

自定义注解说明: https://blog.csdn.net/qq_41463655/article/details/102640063
通过spring aop 通知完成手写事务框架

1、pom.xml


		
		
			org.springframework
			spring-core
			3.0.6.RELEASE
		
		
			org.springframework
			spring-context
			3.0.6.RELEASE
		
		
			org.springframework
			spring-aop
			3.0.6.RELEASE
		
		
			org.springframework
			spring-orm
			3.0.6.RELEASE
		
		
			org.aspectj
			aspectjrt
			1.6.1
		
		
			aspectj
			aspectjweaver
			1.5.3
		
		
			cglib
			cglib
			2.1_2
		

		
		
			com.mchange
			c3p0
			0.9.5.2
		
		
		
		
			mysql
			mysql-connector-java
			8.0.16
		
	


2、spring.xml



	
	 

	
	
		
		
		
		
	

	
	
		
	

	
	
		
	
	
	

3、获取手动事务控制权

// 编程事务(需要手动begin 手动回滚 手都提交)
@Component
@Scope("prototype") // 每个事务都是新的实例 目的解决线程安全问题 多例子
public class TransactionUtils {

	// 全局接受事务状态
	private TransactionStatus transactionStatus;
	// 获取事务源
	@Autowired
	private DataSourceTransactionManager dataSourceTransactionManager;

	// 开启事务
	public TransactionStatus begin() {
		System.out.println("开启事务");
		transactionStatus = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
		return transactionStatus;
	}

	// 提交事务
	public void commit(TransactionStatus transaction) {
		System.out.println("提交事务");
		dataSourceTransactionManager.commit(transaction);
	}

	// 回滚事务
	public void rollback() {
		System.out.println("回滚事务...");
		dataSourceTransactionManager.rollback(transactionStatus);
	}

}

4、ExtTransaction ,自定义事务注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// 事务注解 设置传播行为
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtTransaction {

}

5、AopExtTransaction ,处理事务注解

Aop 中判断是否存在事务注解并处理事务


import com.itmayiedu.annotation.ExtTransaction;
import com.itmayiedu.transaction.TransactionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;

import java.lang.reflect.Method;

//  自定义事务注解具体实现
@Aspect
@Component
public class AopExtTransaction {
	// 一个事务实例子 针对一个事务
	@Autowired
	private TransactionUtils transactionUtils;

	// 使用异常通知进行 回滚事务
	@AfterThrowing("execution(* com.itmayiedu.service.*.*.*(..))")
	public void afterThrowing() {
		// 获取当前事务进行回滚
		// TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		transactionUtils.rollback();
	}



	// 环绕通知 在方法之前和之后处理事情
	@Around("execution(* com.itmayiedu.service.*.*.*(..))")
	public void around(ProceedingJoinPoint pjp) throws Throwable {

		// 1.获取该方法上是否加上注解
		ExtTransaction extTransaction = getMethodExtTransaction(pjp);
		// 2、判断是否存在事务,存在开启事务
		TransactionStatus transactionStatus = begin(extTransaction);
		// 3、调用目标代理对象方法
		pjp.proceed();
		// 4.判断是否存在事务,存在提交事务
		commit(transactionStatus);
	}



	//判断是否存在事务注解,存在开启事务
	private TransactionStatus begin(ExtTransaction extTransaction) {
		if (extTransaction == null) {
			return null;
		}
		// 如果存在事务注解,开启事务
		return transactionUtils.begin();
	}



    //判断是否存在事务注解,存在提交事务
	private void commit(TransactionStatus transactionStatus) {
		if (transactionStatus != null) {
			// 如果存在注解,提交事务
			transactionUtils.commit(transactionStatus);
		}

	}



    // 获取方法上是否存在事务注解
    private ExtTransaction getMethodExtTransaction(ProceedingJoinPoint pjp)
            throws NoSuchMethodException, SecurityException {
        String methodName = pjp.getSignature().getName();
        // 获取目标对象
        Class classTarget = pjp.getTarget().getClass();
        // 获取目标对象类型
        Class[] par = ((MethodSignature) pjp.getSignature()).getParameterTypes();
        // 获取目标对象方法
        Method objMethod = classTarget.getMethod(methodName, par);
        //是否存在事务注解,不存在为null
        ExtTransaction extTransaction = objMethod.getDeclaredAnnotation(ExtTransaction.class);
        return extTransaction;
    }
}

UserDao , 添加add 方法添加表数据

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDao {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	public void add(String name, Integer age) {
		String sql = "INSERT INTO t_users(NAME, age) VALUES(?,?);";
		int updateResult = jdbcTemplate.update(sql, name, age);
		System.out.println("updateResult:" + updateResult);
	}
}

UserServiceImpl --> 模拟事务使用

    @Transaction         // spring 事务注解
	@ExtTransaction      // 自定义事务注解,通过aop实现
	public void add() {
		userDao.add("test001", 20);
		// int i = 1 / 0;
		System.out.println("################");
		userDao.add("test002", 21);
	}

main 方法调用UserService 方法

	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
		UserService userService = (UserService) applicationContext.getBean("userServiceImpl");
		userService.add();
	}

你可能感兴趣的:(#,源码分析)