SpringBoot AOP 面向切面编程

使用的业务场景

  • 日志
  • 权限管理
  • 事务管理
  • 审计
  • 缓存 : 对业务方法返回的结果进行缓存,如何请求参数一样,就直接返回缓存

execution

execution(<修饰符模式>?<返回类型模式><方法名模式>(<参数模式>)<异常模式>?) 除了返回类型模式、方法名模式和参数模式外,其它项都是可选的

完整代码

AOP: https://gitee.com/bseaworkspace/springboot2-2020/tree/master/springboot2AOP

SpringBoot2 学习: https://gitee.com/bseaworkspace/springboot2-2020

package com.xsz.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Configuration;

@Aspect
@Configuration
public class BeforeExample {
	
	//com.xsz.controller下面所有无参的方法执行之前,
	//都会先执行这个方法
	
	/**
	 * execution(* com.xsz.controller.*.*())
	 *  第一个* 表示方法的返回类型,*表示任意类型
	 * com.xsz.controller 表示包的名字
	 * 第二个*表示类的名字,*表示任意类名字
	 * 第三个*必须是()之前,表示方法的名字,*表示任意方法名字
	 * () 表示方法没有输入参数, 
	 * (..) 表示方法有多个参数
	 *  (*)  表示方法有一个参数,参数类型任意
	 */
	@Before("execution(* com.xsz.controller.*.*())")
    public void doCheck1() {
        // ...
		System.out.println("spring的 AOP @Before检测到无参的方法 被执行了");
		
    }

	
	
	@Before("execution(* com.xsz.controller.*.*(*))")
    public void doCheck2() {
        // ...
		System.out.println("spring的 AOP @Before检测到有一个参数的方法 被执行了");
		
    }
}

package com.xsz.aspect;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Configuration;

@Aspect
@Configuration
public class AfterExample {
	
	//com.xsz.controller下面所有无参的方法执行之前,
	//都会先执行这个方法
	
	/**
	 * execution(* com.xsz.controller.*.*())
	 *  第一个* 表示方法的返回类型,*表示任意类型
	 * com.xsz.controller 表示包的名字
	 * 第二个*表示类的名字,*表示任意类名字
	 * 第三个*必须是()之前,表示方法的名字,*表示任意方法名字
	 * () 表示方法没有输入参数, 
	 * (..) 表示方法有多个参数
	 *  (*)  表示方法有一个参数,参数类型任意
	 */
	@AfterReturning("execution(* com.xsz.controller.*.*())")
    public void doCheck1() {
        // ...
		System.out.println("spring的 AOP @AfterReturning 检测到无参的方法 被执行了");
		
    }

	
	
	@AfterReturning("execution(* com.xsz.controller.*.*(*))")
    public void doCheck2() {
        // ...
		System.out.println("spring的 AOP @AfterReturning 检测到有一个参数的方法 被执行了");
		
    }
}

你可能感兴趣的:(SpringBoot)