Spring - handwritten spring annotation version transaction, seven communication behaviors of spring things

I. annotations

1. What is built-in annotation

  • (1) Add @ SuppressWarnings to the front of the program to remove warnings in javac compilation -- stage is SOURCE
  • (2) @ Deprecated package with tag, method, field description obsolete -- stage is SOURCE
  • (3) Mark @ excessive to indicate that the method overrides the method of the parent class -- stage is SOURCE

1.1 @ excessive case demonstration

	@Override
	public String toString() {
		return null;
	}

1.2 @ Deprecated case demonstration indicates that this method has been abandoned

	new Date().parse("");

If deprecated, a strikethrough appears on the call

1.3 @ SuppressWarnings case demonstration

	@SuppressWarnings({ "all" })
	public void save() {
		java.util.List list = new ArrayList();
	}

2. Implement custom annotations

The function of meta annotation is to annotate other annotations. Java 5.0 defines four standard meta annotation types, which are used to provide explanations for other annotation types. Meta annotation defined in Java 5.0:

2.1,@Target

@Target describes the object scope decorated by Annotation: Annotation can be used for packages, types (class, interface, enumeration, Annotation type), type members (method, constructor, member variable, phyll value), method parameters and local variables (such as loop variable, catch parameter). Target is used in the declaration of Annotation type to make its decorated target clearer.

  1. CONSTRUCTOR: used to describe the CONSTRUCTOR
  2. FIELD: used to describe a FIELD
  3. Local "variable: used to describe local variables
  4. METHOD: used to describe a METHOD
  5. PACKAGE: used to describe a PACKAGE
  6. PARAMETER: used to describe parameters
  7. TYPE: used to describe class, interface (including annotation TYPE) or enum declaration

2.2,@Retention

Indicates the level at which the annotation information needs to be saved to describe the annotation life cycle (i.e. the scope of the described annotation)

2.3,@Documented

2.4,@Inherited

Use @ interface to define annotations.

@Target(value = ElementType.METHOD )
@Retention(RetentionPolicy.RUNTIME)
// @interface definition annotation
public @interface AddAnnotation {

    // Handwritten Spring transaction annotation
    int userId() default 0;

    String userName() default "Default name";

    String[] arrays();

}

Reflection reading annotation information


	public static void main(String[] args) throws ClassNotFoundException {
		Class classInfo = Class.forName("com.codeobj.entity.User");
		// Get all methods
		Method[] methods = classInfo.getDeclaredMethods();
		for (Method method : methods) {
			System.out.println(method);
			AddAnnotation declaredAnnotation = method.getDeclaredAnnotation(AddAnnotation.class);
			if (declaredAnnotation == null) {
				// End this cycle
				continue;
			}
			// Get userId
			int userId = declaredAnnotation.userId();
			System.out.println("userId:" + userId);
			// Get userName
			String userName = declaredAnnotation.userName();
			System.out.println("userName:" + userName);
			// Get arrays
			String[] arrays = declaredAnnotation.arrays();
			for (String str : arrays) {
				System.out.println("str:" + str);
			}
		}
	}

3. Custom transaction annotation

//Programming transactions (manual begin is required, manual rollback is required, and both hands commit)
@Component()
@Scope("prototype") // Setting up prototype to solve thread safety
public class TransactionUtils {

	private TransactionStatus transactionStatus;
	// Get transaction source
	@Autowired
	private DataSourceTransactionManager dataSourceTransactionManager;

	// Open transaction
	public TransactionStatus begin() {
		transactionStatus = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
		return transactionStatus;
	}

	// Submission of affairs
	public void commit(TransactionStatus transaction) {
		dataSourceTransactionManager.commit(transaction);
	}

	// Rollback transaction
	public void rollback() {
		System.out.println("rollback");
		dataSourceTransactionManager.rollback(transactionStatus);
	}

}

//Annotation

@Autowired
	private TransactionUtils transactionUtils;

	@AfterThrowing("execution(* com.codeobj.service.*.*.*(..))")
	public void afterThrowing() throws NoSuchMethodException, SecurityException {
		// isRollback(proceedingJoinPoint);
		System.out.println("Program exception");
		// TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		// TransactionStatus currentTransactionStatus =
		// TransactionAspectSupport.currentTransactionStatus();
		// System.out.println("currentTransactionStatus:" +
		// currentTransactionStatus);
		transactionUtils.rollback();
	}

	// //Circular notification handles things before and after methods
	@Around("execution(* com.codeobj.service.*.*.*(..))")
	public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

		// Execute before calling method
		TransactionStatus transactionStatus = begin(proceedingJoinPoint);
		proceedingJoinPoint.proceed();// Note for agent calling method: if the calling method throws an exception, the following code will not be executed
		// Execute after method call
		commit(transactionStatus);
	}

	public TransactionStatus begin(ProceedingJoinPoint pjp) throws NoSuchMethodException, SecurityException {

		// //Determine whether there is a custom transaction annotation
		ExtTransaction declaredAnnotation = getExtTransaction(pjp);
		if (declaredAnnotation == null) {
			return null;
		}
		// If there is a custom transaction annotation, open the transaction
		System.out.println("Open transaction");
		TransactionStatus transactionStatu = transactionUtils.begin();
		return transactionStatu;
	}

	public void commit(TransactionStatus transactionStatu) {
		if (transactionStatu != null) {
			// Submission of affairs
			System.out.println("Submission of affairs");
			transactionUtils.commit(transactionStatu);
		}
	}

	public ExtTransaction getExtTransaction(ProceedingJoinPoint pjp) throws NoSuchMethodException, SecurityException {
		// Get method name
		String methodName = pjp.getSignature().getName();
		// Get target object
		Class<?> classTarget = pjp.getTarget().getClass();
		// Get target object type
		Class<?>[] par = ((MethodSignature) pjp.getSignature()).getParameterTypes();
		// Get target object method
		Method objMethod = classTarget.getMethod(methodName, par);
		// //Determine whether there is a custom transaction annotation
		ExtTransaction declaredAnnotation = objMethod.getDeclaredAnnotation(ExtTransaction.class);
		if (declaredAnnotation == null) {
			System.out.println("Your method,No comments added!");
			return null;
		}
		return declaredAnnotation;

	}

	// Rollback transaction
	public void isRollback(ProceedingJoinPoint pjp) throws NoSuchMethodException, SecurityException {
		// //Determine whether there is a custom transaction annotation
		ExtTransaction declaredAnnotation = getExtTransaction(pjp);
		if (declaredAnnotation != null) {
			System.out.println("Started rolling back transaction");
			// Get current transaction rollback directly
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return;
		}
	}


Use custom annotations

@ExtTransaction
public void add() {
	userDao.add("test001", 20);
	int i = 1 / 0;
	System.out.println("################");
	userDao.add("test002", 21);
}

2, Seven communication behaviors of Spring things

The definition of transaction in Spring:

Propagation (the key attribute determines which method the agent should add transaction behavior to. The most important part of such attributes is communication behavior.) The following options are available:

The default propagation behavior is REQUIRED

  • Promotion ﹣ required - if there is a current transaction, use the current transaction, if there is no current transaction, create a new transaction. This is the most common choice.
  • Promotion? Supports -- supports the current transaction. If there is no current transaction, it will be executed in a non transactional manner. //If the outer method does not have a transaction, it is executed as a non transaction.
  • Promotion menu management -- supports the current transaction. If there is no current transaction, an exception will be thrown.  
  • Promotion ﹣ requests ﹣ new -- creates a new transaction, and suspends the current transaction if it currently exists.  
  • Promotion not supported -- performs the operation in a non transactional manner, and suspends the current transaction if it currently exists. ---If there is currently a transaction, it is executed as a non transaction
  • Promotion? Never -- execute in a non transactional manner, throw an exception if there is currently a transaction.

Personal blog Snail

Tags: Programming Java Spring Attribute

Posted on Sun, 19 Jan 2020 21:53:13 -0500 by winsonlee