持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第25天,点击查看活动详情
1 通知
package site.exciter.spring.aop.impl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
/**
* @Aspect当前类声明成一个切面
*/
@Component
@Aspect
public class LoggingAspect {
/**
* 前置通知:在目标方法开始执行之前执行
* <p>
* execution(* site.exciter.spring.aop.impl. * . * (..))
* 第一个*表示方法修饰符和反参可以为任意类型,
* 第二个*代表该包下所有的类,
* 第三个*表示所有的方法
* 括号中的..表示目标方法的入参
*
* @param point 连接信息
*/
@Before("execution(* site.exciter.spring.aop.impl.*.*(..))")
public void beforeMethod(JoinPoint point) {
String methodName = point.getSignature().getName();
List<Object> args = Arrays.asList(point.getArgs());
System.out.println("The method " + methodName + " begin with " + args);
}
/**
* 后置通知:在目标方法执行后(无论是否发生异常)执行的通知
* 在后置通知中还不能访问目标方法执行的结果
*
* @param point 连接信息
*/
@After("execution(* site.exciter.spring.aop.impl.*.*(..))")
public void afterMethod(JoinPoint point) {
String methodName = point.getSignature().getName();
System.out.println("The method " + methodName + " end");
}
/**
* 返回通知:在方法正常结束后执行,可以访问到目标方法的返回值
*
* @param point 连接信息
* @param result 返回结果
*/
@AfterReturning(value = "execution(* site.exciter.spring.aop.impl.*.*(..))", returning = "result")
public void afterReturning(JoinPoint point, Object result) {
String methodName = point.getSignature().getName();
System.out.println("The method " + methodName + " end with " + result);
}
/**
* 异常通知:在方法发生异常的时候执行,可以访问到异常对象
*
* @param point 连接信息
* @param exception 异常信息
*/
@AfterThrowing(value = "execution(* site.exciter.spring.aop.impl.*.*(..))", throwing = "exception")
public void afterThrowing(JoinPoint point, Exception exception) {
String methodName = point.getSignature().getName();
System.out.println("The method " + methodName + " occurs exception: " + exception);
}
/**
* 环绕通知:类似于动态代理的全过程
* 环绕通知必须有返回值,返回值即为目标方法的返回值
*
* @param point ProceedingJoinPoint
*/
@Around("execution(* site.exciter.spring.aop.impl.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint point) {
Object result = null;
String methodName = point.getSignature().getName();
List<Object> args = Arrays.asList(point.getArgs());
try {
//前置通知
System.out.println("The method " + methodName + " begin with " + args);
//执行目标方法
result = point.proceed();
//返回通知
System.out.println("The method " + methodName + " end with " + result);
} catch (Throwable e) {
//异常通知
System.out.println("The method " + methodName + " occurs exception: " + e);
e.printStackTrace();
}
//后置通知
System.out.println("The method " + methodName + " end ");
return result;
}
}
2 切片优先级
使用@Order(value)来指定切面的优先级,值越小,优先级越高。
验证切面ValidationAspect
package site.exciter.spring.aop.impl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* 可以使用@Order(value)来指定切面的优先级,值越小,优先级越高
*/
@Order(1)
@Aspect
@Component
public class ValidationAspect {
@Before("execution(* site.exciter.spring.aop.impl.*.*(..))")
public void validationArgs(JoinPoint point) {
System.out.println("---> validation:" + Arrays.asList(point.getArgs()));
}
}
日志切面LoggingAspect
package site.exciter.spring.aop.impl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
/**
* @Aspect当前类声明成一个切面
*/
@Order(2)
@Aspect
@Component
public class LoggingAspect {
/**
* 前置通知:在目标方法开始执行之前执行
* <p>
* execution(* site.exciter.spring.aop.impl. * . * (..))
* 第一个*表示方法修饰符和反参可以为任意类型,
* 第二个*代表该包下所有的类,
* 第三个*表示所有的方法
* 括号中的..表示目标方法的入参
*
* @param point 连接信息
*/
@Before("execution(* site.exciter.spring.aop.impl.*.*(..))")
public void beforeMethod(JoinPoint point) {
String methodName = point.getSignature().getName();
List<Object> args = Arrays.asList(point.getArgs());
System.out.println("The method " + methodName + " begin with " + args);
}
}
结果:
---> validation:[3, 6]
The method add begin with [3, 6]
3 复用切点表达式
1、定义一个方法,使用@Pointcut注解来声明切入表达式。
/**
* 定义一个方法,专门用来声明切入点表达式,该方法中无需其他代码。
* 使用@Pointcut来声明切入表达式。
*/
@Pointcut("execution(* site.exciter.spring.aop.impl.*.*(..))")
public void declareJoinPointExpression() {
}
2、在其他通知方法中引入1中定义的方法名。
@Before("declareJoinPointExpression()")
public void beforeMethod(JoinPoint point) {
String methodName = point.getSignature().getName();
List<Object> args = Arrays.asList(point.getArgs());
System.out.println("The method " + methodName + " begin with " + args);
}
示例:
package site.exciter.spring.aop.impl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
/**
* @Aspect当前类声明成一个切面
*/
@Order(2)
@Aspect
@Component
public class LoggingAspect {
/**
* 定义一个方法,专门用来声明切入点表达式,该方法中无需其他代码。
* 使用@Pointcut来声明切入表达式。
*/
@Pointcut("execution(* site.exciter.spring.aop.impl.*.*(..))")
public void declareJoinPointExpression() {
}
/**
* 前置通知:在目标方法开始执行之前执行
* <p>
* execution(* site.exciter.spring.aop.impl. * . * (..))
* 第一个*表示方法修饰符和反参可以为任意类型,
* 第二个*代表该包下所有的类,
* 第三个*表示所有的方法
* 括号中的..表示目标方法的入参
*
* @param point 连接信息
*/
@Before("declareJoinPointExpression()")
public void beforeMethod(JoinPoint point) {
String methodName = point.getSignature().getName();
List<Object> args = Arrays.asList(point.getArgs());
System.out.println("The method " + methodName + " begin with " + args);
}
/**
* 后置通知:在目标方法执行后(无论是否发生异常)执行的通知
* 在后置通知中还不能访问目标方法执行的结果
*
* @param point 连接信息
*/
@After("declareJoinPointExpression()")
public void afterMethod(JoinPoint point) {
String methodName = point.getSignature().getName();
System.out.println("The method " + methodName + " end");
}
/**
* 返回通知:在方法正常结束后执行,可以访问到目标方法的返回值
*
* @param point 连接信息
* @param result 返回结果
*/
@AfterReturning(value = "declareJoinPointExpression()", returning = "result")
public void afterReturning(JoinPoint point, Object result) {
String methodName = point.getSignature().getName();
System.out.println("The method " + methodName + " end with " + result);
}
/**
* 异常通知:在方法发生异常的时候执行,可以访问到异常对象
*
* @param point 连接信息
* @param exception 异常信息
*/
@AfterThrowing(value = "declareJoinPointExpression()", throwing = "exception")
public void afterThrowing(JoinPoint point, Exception exception) {
String methodName = point.getSignature().getName();
System.out.println("The method " + methodName + " occurs exception: " + exception);
}
/**
* 环绕通知:类似于动态代理的全过程
* 环绕通知必须有返回值,返回值即为目标方法的返回值
*
* @param point ProceedingJoinPoint
*/
@Around("declareJoinPointExpression()")
public Object aroundMethod(ProceedingJoinPoint point) {
Object result = null;
String methodName = point.getSignature().getName();
List<Object> args = Arrays.asList(point.getArgs());
try {
//前置通知
System.out.println("The method " + methodName + " begin with " + args);
//执行目标方法
result = point.proceed();
//返回通知
System.out.println("The method " + methodName + " end with " + result);
} catch (Throwable e) {
//异常通知
System.out.println("The method " + methodName + " occurs exception: " + e);
e.printStackTrace();
}
//后置通知
System.out.println("The method " + methodName + " end ");
return result;
}
}
package site.exciter.spring.aop.impl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* 可以使用@Order(value)来指定切面的优先级,值越小,优先级越高
*/
@Order(1)
@Aspect
@Component
public class ValidationAspect {
/**
* 引入其他包或类下的切入点方法,需要加上包名或类名
*
* @param point
*/
@Before("site.exciter.spring.aop.impl.LoggingAspect.declareJoinPointExpression()")
public void validationArgs(JoinPoint point) {
System.out.println("---> validation:" + Arrays.asList(point.getArgs()));
}
}
4 配置文件的方式配置AOP
1 代码中不使用任何注解
package site.exciter.spring.aop.xml;
public interface IArithmeticCalculator {
int add(int i, int j);
int sub(int i, int j);
int mul(int i, int j);
int div(int i, int j);
}
package site.exciter.spring.aop.xml;
public class ArithmeticCalculatorImpl implements IArithmeticCalculator {
@Override
public int add(int i, int j) {
return i + j;
}
@Override
public int sub(int i, int j) {
return i - j;
}
@Override
public int mul(int i, int j) {
return i * j;
}
@Override
public int div(int i, int j) {
return i / j;
}
}
package site.exciter.spring.aop.xml;
import org.aspectj.lang.JoinPoint;
import java.util.Arrays;
public class ValidationAspect {
public void validationArgs(JoinPoint point) {
System.out.println("---> validation:" + Arrays.asList(point.getArgs()));
}
}
package site.exciter.spring.aop.xml;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import java.util.Arrays;
import java.util.List;
public class LoggingAspect {
public void beforeMethod(JoinPoint point) {
String methodName = point.getSignature().getName();
List<Object> args = Arrays.asList(point.getArgs());
System.out.println("The method " + methodName + " begin with " + args);
}
public void afterMethod(JoinPoint point) {
String methodName = point.getSignature().getName();
System.out.println("The method " + methodName + " end");
}
public void afterReturning(JoinPoint point, Object result) {
String methodName = point.getSignature().getName();
System.out.println("The method " + methodName + " end with " + result);
}
public void afterThrowing(JoinPoint point, Exception exception) {
String methodName = point.getSignature().getName();
System.out.println("The method " + methodName + " occurs exception: " + exception);
}
public Object aroundMethod(ProceedingJoinPoint point) {
Object result = null;
String methodName = point.getSignature().getName();
List<Object> args = Arrays.asList(point.getArgs());
try {
//前置通知
System.out.println("The method " + methodName + " begin with " + args);
//执行目标方法
result = point.proceed();
//返回通知
System.out.println("The method " + methodName + " end with " + result);
} catch (Throwable e) {
//异常通知
System.out.println("The method " + methodName + " occurs exception: " + e);
e.printStackTrace();
}
//后置通知
System.out.println("The method " + methodName + " end ");
return result;
}
}
2 在配置文件中配置AOP
applicationContext-xml.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!-- 配置Bean -->
<bean id="arithmeticCalculator" class="site.exciter.spring.aop.xml.ArithmeticCalculatorImpl"/>
<!-- 配置切面的Bean -->
<bean id="loggingAspect" class="site.exciter.spring.aop.xml.LoggingAspect"/>
<bean id="validationAspect" class="site.exciter.spring.aop.xml.ValidationAspect"/>
<!-- 配置AOP -->
<aop:config>
<!-- 配置切面表达式 -->
<aop:pointcut id="pointcut" expression="execution(* site.exciter.spring.aop.xml.*.*(..))"/>
<!-- 配置切面及通知 -->
<aop:aspect ref="validationAspect" order="1">
<!-- 配置切面方法 -->
<aop:before method="validationArgs" pointcut-ref="pointcut"/>
</aop:aspect>
<aop:aspect ref="loggingAspect" order="2">
<aop:before method="beforeMethod" pointcut-ref="pointcut"/>
<aop:after method="afterMethod" pointcut-ref="pointcut"/>
<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="exception"/>
</aop:aspect>
</aop:config>
</beans>
3 测试
package site.exciter.spring.aop.xml;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
@org.junit.Test
public void testImpl() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-xml.xml");
IArithmeticCalculator calculator = (IArithmeticCalculator) context.getBean("arithmeticCalculator");
int result = calculator.add(3, 6);
System.out.println("result-->" + result);
result = calculator.div(12, 2);
System.out.println("result-->" + result);
}
}
关注木水小站 (zhangmushui.cn)和微信公众号【木水Code】,及时获取更多最新技术干货。