[Spring] Spring AOP's acquaintance

What is AOP

AOP is an abbreviation for Aspect Oriented Programming, meaning: Aspect Oriented Programming, Spring provides rich support for aspect-oriented programming, allowing for the development of cohesive application by the separation of business logic and system-level services.

Why AOP

Application object is only realized they should do - to complete the business logic - nothing more. AOP can use to isolate each part of the business logic such that the business logic to reduce the degree of coupling between the parts, improve the reusability of the program, code to simplify and improve the efficiency of development. If you do not use AOP, for example, business logic code for the following:

package cn.jingpengchong.calculator.service;

import org.springframework.stereotype.Service;

@Service
public class CalculatorService implements ICalculatorService {

	public int div(int a, int b) {
		System.out.println("日志:The div method begins");
		System.out.println("日志:The div method args:["+a+","+b+"]");
		return a/b;
	}
}

This embodiment does not use Spring AOP function, and therefore only the main method of "return a / b;" This one, however, to print log information, it takes two lines of code, is particularly bulky. If we are then expanded and a multiplication function, you still need to write two lines of code, which is very cumbersome. So how to solve such a complicated thing? Of course, it is to use AOP functionality provided by a spring.

How to use AOP: use annotations

After the required jar package into the current project, initially charged in the xml configuration file "<aop: aspectj-autoproxy />" tag, followed by the preparation of the business process requires independent cutting modules (also referred to as section) and the entry point (block method), add "@Aspect" annotation and which can be scanned into the IOC containers separate annotation module before the class, add annotations processing method corresponding to an entry point in the previous method i.e.

Remarks before the entry points are the following:
  • @Before (value = ""): pre-processing, for some operations before performing the method of the matching annotations;
  • @After (value = ""): post-processing, for performing some operations in the execution of the method of the matching annotations;
  • @AfterReturning (value = "", returning = ""): return processing for performing some operations in the method returns the result of the matching annotations;
  • @AfterThrowing (value = "", throwing = ""): exception handling, for the annotation matching method after return some abnormality;
  • @Around (value = ""): surround processing, can be processed in the code self related links on demand.
Note:
  • A method for matching attribute value to be processed;
  • returning means for receiving a return value attribute;
  • throwing attribute for receiving exception object;
  • @After and @AfterReturning difference:
    • @After annotated method performed prior to the method @AfterReturning annotations;
    • @ In the face of an exception, the method After annotated still perform, but @AfterReturning annotated method does.
Example: were used @ Before, @ After, @ AfterReturning @Around annotations and all aspects of the service layer above processing method performed
1, the method of service layer code printing log deleted
package cn.jingpengchong.calculator.service;

import org.springframework.stereotype.Service;

@Service
public class CalculatorService implements ICalculatorService {

	public int div(int a, int b) {
		return a/b;
	}
}
2, add the label in the spring xml file: Automatic Proxy
<aop:aspectj-autoproxy/>
3, new independent modules "cn.jingpengchong.aspect", in which the new file "CalculatorService.java" as follows:
package cn.jingpengchong.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CalculatorAspect {

	//前置处理
	@Before("execution(public int cn.jingpengchong.calculator.service.CalculatorService.*(..))")
	public void before(JoinPoint jp) {
		Object[] args = jp.getArgs();
		Signature signature = jp.getSignature();
		String name = signature.getName();
		System.out.println("日志:The " + name + " method begins");
		System.out.println("日志:The " + name + " method args:[" + args[0] + "," + args[1] + "]");
	}
	
	//后置处理
	@After("execution(public int cn.jingpengchong.calculator.service.CalculatorService.*(..))")
	public void after(JoinPoint jp) {
		Signature signature = jp.getSignature();
		String name = signature.getName();
		System.out.println("日志:The " + name + " method ends");
	}
	
	//返回处理
	@AfterReturning(value = "execution(public int cn.jingpengchong.calculator.service.CalculatorService.*(..))", returning = "result")
	public void afterReturning(JoinPoint jp, Object result) {
		Signature signature = jp.getSignature();
		String name = signature.getName();
		System.out.println("日志:The " + name + " method result:" + result);
	}
	
	//异常处理
	@AfterThrowing(value = "execution(public int cn.jingpengchong.calculator.service.CalculatorService.*(..))", throwing = "e")
	public void afterThrowing(JoinPoint jp, Exception e) {
		Signature signature = jp.getSignature();
		String name = signature.getName();
		System.out.println("日志:The " + name + " method exception:" + e);
	}
}
4, preparation of test categories:
package cn.jingpengchong.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.jingpengchong.calculator.service.ICalculatorService;

public class Test {
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
		ICalculatorService calculatorService = applicationContext.getBean(ICalculatorService.class);
		System.out.println(calculatorService.div(6, 2));
		applicationContext.close();
	}
}

Results are as follows:
Here Insert Picture Description

Attachment:

1, the above "CalculatorService.java" file in each method should write notes with a long argument, we can define the file in a cut-off point to extract the parameters of these annotations:

@Pointcut("execution(public int cn.jingpengchong.calculator.service.CalculatorService.*(..))")
public void pointCut() {		
}

In this case the parameters of the above comments can be written "pointCut ()", to further simplify the code.
2, if that method is too cumbersome define four In "CalculatorService.java" file, you can use "@Around" annotation process encapsulated in one method:

//环绕处理
@Around("pointCut()")
public Object around(ProceedingJoinPoint pjp) {
	Object result = null;
	Object[] args = pjp.getArgs();
	String name = pjp.getSignature().getName();
	try {
		try {
			//前置处理
			System.out.println("The " + name + " method begins");
			System.out.println("The " + name + " method args:[" + args[0] + "," + args[1] + "]");
			result = pjp.proceed();
		}finally {
			//后置处理
			System.out.println("The " + name + " method ends");
		}
		//返回处理
		System.out.println("The " + name + " method result:" + result);
	} catch (Throwable e) {
		//异常处理
		System.out.println("The " + name + " method exception:" + e);
	}
	return result;
}

xml configuration file using the spring: how to use AOP

Also need the required jar package into the current project

1, still the log processing service layer method as an example:
package cn.jingpengchong.calculator.service;

import org.springframework.stereotype.Service;

@Service
public class CalculatorService implements ICalculatorService {
	public int div(int a, int b) {
		return a/b;
	}
}
2, new independent modules "cn.jingpengchong.aspect", in which the new file "LogAspect.java" as follows:
package cn.jingpengchong.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;

public class LogAspect {

	public void before(JoinPoint jp) {
		Object[] args = jp.getArgs();
		Signature signature = jp.getSignature();
		String name = signature.getName();
		System.out.println("日志:The " + name + " method begins");
		System.out.println("日志:The " + name + " method args:[" + args[0] + "," + args[1] + "]");
	}
}
3, following configurations spring xml configuration file:
<?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: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-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

	<context:component-scan base-package="cn.jingpengchong"></context:component-scan>
 
	<bean id = "logAspect" class = "cn.jingpengchong.aspect.LogAspect"/>
	
	<aop:config>
		<!--该标签是为了简化代码,指定一个id来表示该表达式,下面再引用时,直接用该id就行了-->
		<aop:pointcut expression="execution(public int cn.jingpengchong.calculator.service.CalculatorService.*(..))" id="pointCut"/>
		<aop:aspect ref="logAspect">
			<!--以前置处理为例,其他处理类似-->
			<aop:before method="before" pointcut-ref="pointCut"/>
		</aop:aspect>
	</aop:config>
</beans>
4, preparation of test categories:
package cn.jingpengchong.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.jingpengchong.calculator.service.ICalculatorService;

public class Test {
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
		ICalculatorService calculatorService = applicationContext.getBean(ICalculatorService.class);
		System.out.println(calculatorService.div(6, 2));
		applicationContext.close();
	}
}

Results are as follows:
Here Insert Picture Description

Published 128 original articles · won praise 17 · views 2735

Guess you like

Origin blog.csdn.net/qq_43705275/article/details/104174163