Spring Aop - Aspect 使用方法
在配置类中使用 @EnableAspectJAutoProxy 才能使Aspect生效,在这篇文章中详细分析该注解的作用原理。
切面类使用 @Aspect 声明,同时需要@Component注册为组件(或用其他方式,Aspect不会自动注册为Spring组件)
切面类有以下主要功能(用法详见代码部分):
- @PointCut:使用execution切入表达式声明需要增强的方法(其他注解也可直接声明,但为了防止代码冗余,可使用此注解标注一个方法,再在其他注解中直接引用该方法即可)
- @Before:方法执行前调用
- @After:方法执行后调用
- @AfterReturning:方法返回结果后调用(执行后),returning参数指定返回结果
- @AfterThrowing:抛出异常后调用,throwing参数指定异常信息
- @Around:环绕通知,可以手动调用方法执行并返回结果,使用ProceedingJoinPoint参数调用。
- JoinPoint:可作为被标注的方法的参数传入,有很多有用的get方法
例子:
先看结果


简要代码
切面类:
@Aspect
@Component
public class Log {
@Pointcut(value = "execution(public int cap.other.Div.*(..))")
private void pointCut(){}
@Before("pointCut()")
private void logStart(@NotNull JoinPoint joinPoint){
System.out.println("Start>>> Args:" + Arrays.asList(joinPoint.getArgs()));
}
@After(value = "pointCut()")
private void logEnd(){
System.out.println("<<<End");
}
@AfterReturning(value = "pointCut()", returning = "result")
private void logReturn(Object result){
System.out.println("---Return:" + result);
}
@AfterThrowing(value = "pointCut()", throwing = "exception")
private void logException(Throwable exception){
System.out.println("!exception:" + exception);
}
@Around("pointCut()")
private Object logAround(@NotNull ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("====Before Around====");
Object result = proceedingJoinPoint.proceed();
System.out.println("====After Around====");
return result;
}
}
需要增强的类:
@Component
public class Div {
public int div(int a, int b){
System.out.println("进入方法,开始执行");
int res = a/b;
System.out.println("执行结束---result:" + res);
return res;
}
}
Test:
@Test
public void test() {
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(MainConfig.class);
Div div = app.getBean(Div.class);
div.div(4,2);
}
Config类:
@Configuration
@ComponentScan(value = {"cap"} //cap是包名
@EnableAspectJAutoProxy
public class MainConfig {}
maven:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>

浙公网安备 33010602011771号