1.AOP是什么?
1.是一种编程范式,不是编程语言
2.解决特定问题,不能解决所有问题
3.是OOP(Object Oriented Programming)的补充,不是替代
五个注解:
- 前置通知(Before):在目标方法被调用之前调用通知功能;
- 后置通知(After):在目标方法完成之后调用通知,此时不会关心方法的输出是什么;
- 返回通知(After-returning):在目标方法成功执行之后调用通知;
- 异常通知(After-throwing):在目标方法抛出异常后调用通知;
- 环绕通知(Around):通知包裹了被通知的方法,在被通知的方法调用之前和调用之后执行自定义的行为。
2.Aop使用前后对比
2.1 使用Aop前
所需要的依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>
先看一下代码结构
@Datapublic class Product {private Long id;private String name;}
public class CurrentUserHolder {private static final ThreadLocal<String> holder = new ThreadLocal<>();public static String get() {return holder.get() == null ? "unknown" : holder.get();}public static void set(String user) {holder.set(user);}}
@Componentpublic class AuthService {public void checkAccess() {String user = CurrentUserHolder.get();if (!"admin".equals(user)) {throw new RuntimeException("operation not allow");}}}
现在的需求是这两个方法都需要经过校验,身份是admin才能执行,这种写法相当于硬编码,假设我300个方法都需要校验的情况,那我需要一条条的添加到方法中去。
@Service@Slf4jpublic class ProductService {@AutowiredAuthService authService;public void insert(Product product) {authService.checkAccess();log.info("insert product");}public void delete(Long id) {authService.checkAccess();log.info("delete product");}}
执行测试看一下结果:
@SpringBootTestclass AopApplicationTests {@AutowiredProductService productService;@Testvoid contextLoads() {}@Testpublic void anoInsertTest() {CurrentUserHolder.set("tom");productService.delete(1L);}@Testpublic void adminInsert() {CurrentUserHolder.set("admin");productService.delete(1L);}}
2.2使用Aop后
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface AdminOnly {}
@Aspect@Componentpublic class SecurityAspect {@AutowiredAuthService authService;// 拦截标注AdminOnly的方法@Pointcut("@annotation(AdminOnly)")public void adminOnly(){}// 在执行前插入这行代码@Before("adminOnly()")public void check(){authService.checkAccess();}}
去掉这种硬编码的方式加上注解。
@Service@Slf4jpublic class ProductService {@AdminOnlypublic void insert(Product product) {log.info("insert product");}@AdminOnlypublic void delete(Long id) {log.info("delete product");}}
3.切面表达式

任意公共方法的执行:execution(public * *(..))任何一个以“set”开始的方法的执行:execution(* set*(..))AccountService 接口的任意方法的执行:execution(* com.xyz.service.AccountService.*(..))定义在service包里的任意方法的执行:execution(* com.xyz.service.*.*(..))定义在service包和所有子包里的任意类的任意方法的执行:execution(* com.xyz.service..*.*(..))定义在pointcutexp包和所有子包里的JoinPointObjP2类的任意方法的执行:execution(* com.test.spring.aop.pointcutexp..JoinPointObjP2.*(..))")***> 最靠近(..)的为方法名,靠近.*(..))的为类名或者接口名,如上例的JoinPointObjP2.*(..))pointcutexp包里的任意类.within(com.test.spring.aop.pointcutexp.*)pointcutexp包和所有子包里的任意类.within(com.test.spring.aop.pointcutexp..*)实现了MyInterface接口的所有类,如果MyInterface不是接口,限定MyInterface单个类.this(com.test.spring.aop.pointcutexp.MyInterface)***> 当一个实现了接口的类被AOP的时候,用getBean方法必须cast为接口类型,不能为该类的类型.带有@MyTypeAnnotation标注的所有类的任意方法.@within(com.elong.annotation.MyTypeAnnotation)@target(com.elong.annotation.MyTypeAnnotation)带有@MyTypeAnnotation标注的任意方法.@annotation(com.elong.annotation.MyTypeAnnotation)***> @within和@target针对类的注解,@annotation是针对方法的注解参数带有@MyMethodAnnotation标注的方法.@args(com.elong.annotation.MyMethodAnnotation)参数为String类型(运行是决定)的方法.args(String)
3.1within表达式
@Component@Aspect@Slf4jpublic class PkgTypeAspectConfig {// 匹配类// @Pointcut("within(com.example.aop.service.AuthService)")// 匹配包名下所有的类@Pointcut("within(com.example.aop.service.*)")public void matchType() {}@Before("matchType()")public void before() {log.info("PkgTypeAspectConfig");}}
3.2对象匹配
this匹配实现接口下的所有类
public interface Work {void working();}
@Servicepublic class MondayWorkServiceImpl implements Work {@Overridepublic void working() {}}
@Component@Aspect@Slf4jpublic class ObjectiveAspectConfig {// 匹配Work接口下的所有类@Pointcut("this(com.example.aop.service.Work)")public void matchCondition() {}@Before("matchCondition()")public void before() {log.info("matchCondition");}}
在没有引入Introduction的情况下this和target结果是一样的
@Component@Aspect@Slf4jpublic class ObjectiveAspectConfig {// 匹配Work接口下的所有类@Pointcut("target(com.example.aop.service.Work)")public void matchCondition() {}@Before("matchCondition()")public void before() {log.info("matchCondition");}}
匹配bean注意类名开头小写,我学习过程中因为没有小写导致排查了一小时
@Component@Aspect@Slf4jpublic class ObjectiveAspectConfig {// bean名称@Pointcut("bean(mondayWorkServiceImpl))")public void matchCondition() {}@Before("matchCondition()")public void before() {log.info("matchCondition");}}
3.3参数匹配
@Aspect@Componentpublic class ArgsAspectConfig {// @Pointcut("args(Long,String) && within(com.example.aop.service.*)") 匹配Long,String// @Pointcut("args(Long,..) && within(com.example.aop.service.*)") 匹配Long,和任意类型// @Pointcut("args(..) && within(com.example.aop.service.*)") 匹配任意类型// 匹配long类型@Pointcut("args(*) && within(com.example.aop.service.*)")public void matchArgs() {}@Before("matchArgs()")public void before() {System.out.println("###before");}}
3.4注解方式匹配
@Component@Aspect@Slf4jpublic class AnoAspectConfig {@Pointcut("@annotation(com.example.aop.security.AdminOnly)")public void matchAno(){}@Before("matchAno()")public void before(){System.out.println("AnoAspectConfig");}}
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface AdminOnly {}
添加注解到方法上即可实现拦截
@AdminOnlypublic void delete(Long id) {log.info("delete product");}
可被继承的注解
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Inherited //支持继承public @interface NeedSecured {}
父类
@Service@Slf4j@NeedSecuredpublic class ProductService {@AdminOnlypublic void insert(Product product) {log.info("insert product");}@AdminOnlypublic void delete(Long id) {log.info("delete product");}public void withinTest(){log.info("withinTest");}}
子类继承父类NeedSecured注解也被继承,所以都会匹配成功
@Componentpublic class SubProductService extends ProductService {public void demo() {System.out.println("SubProductService");}}
在spring context的环境下,二者没有区别target和within
@Component@Aspect@Slf4jpublic class AnoAspectConfig {@Pointcut("@target(com.example.aop.security.NeedSecured)")public void matchAno(){}@Before("matchAno()")public void before(){System.out.println("AnoAspectConfig");}}
在类上面添加NeedSecured注解调用改类就会被匹配
@NeedSecuredpublic class Product {}
@Component@Aspect@Slf4jpublic class AnoAspectConfig {@Pointcut("@args(com.example.aop.security.NeedSecured)")public void matchAno(){}@Before("matchAno()")public void before(){System.out.println("AnoAspectConfig");}}
3.5 execution匹配(重点掌握)
@Aspect@Componentpublic class ExecutionAspectConfig {// @Pointcut("execution(public String com.imooc.service..*(..))") 匹配service包含子包且只匹配无返回值// @Pointcut("execution(public String com.imooc.service..*(..))") 匹配service包含子包且只匹配String的返回值// @Pointcut("execution(public * com.imooc.service..*(..))") 匹配service包含子包任意返回值// @Pointcut("execution(public * com.imooc.service..*())") 匹配service包含子包无参数// @Pointcut("execution(public * com.imooc.service..*(Long))") 匹配service包含子包且拦截参数的Long类型// @Pointcut("execution(public * com.imooc.service.*(..) throws java.lang.IllegalAccessException)") 只匹配抛出IllegalAccessException的类// 匹配service下的包不包含子包@Pointcut("execution(public * com.imooc.service.*(..))")public void matchCondition() {}@Before("matchCondition()")public void before() {System.out.println("");System.out.println("###before");}}
还能这样写匹配Note开头的所有类除NoteWeiXinCodeController
@Pointcut("execution(public * com.jideos.jnotes.controller.Note*.*(..))" +"&& !execution(public * com.jideos.jnotes.controller.NoteWeiXinCodeController*.*(..))")public void verify() {}
3.6 advice注解
Around注解可以用来在调用一个具体方法前和调用后来完成一些具体的任务,如下就用获取方法执行时间
@Aspect@Component@Slf4jpublic class TimeInterceptor {// 一分钟,即60000msprivate static final long ONE_MINUTE = 60000;// service层的统计耗时切面,类型必须为final String类型的,注解里要使用的变量只能是静态常量类型的public static final String POINT = "execution (* com.example.aop.*.*(..))";// 统计方法执行耗时Around环绕通知@Around(POINT)public Object timeAround(ProceedingJoinPoint joinPoint) {// 定义返回对象、得到方法需要的参数Object obj = null;Object[] args = joinPoint.getArgs();long startTime = System.currentTimeMillis();try {obj = joinPoint.proceed(args);} catch (Throwable e) {log.error("统计某方法执行耗时环绕通知出错", e);}// 获取执行的方法名long endTime = System.currentTimeMillis();MethodSignature signature = (MethodSignature) joinPoint.getSignature();String methodName = signature.getDeclaringTypeName() + "." + signature.getName();// 打印耗时的信息this.printExecTime(methodName, startTime, endTime);return obj;}// 打印方法执行耗时的信息,如果超过了一定的时间,才打印private void printExecTime(String methodName, long startTime, long endTime) {long diffTime = endTime - startTime;if (diffTime > ONE_MINUTE) {log.warn("-----" + methodName + " 方法执行耗时:" + diffTime + " ms");}}}
