SpringBoot实现AOP引入的依赖
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-aop</artifactId> 4 </dependency>
启动类不需要添加
@ComponentScan("com.only.mate.springboot.aop") @EnableAspectJAutoProxy//开启AspectJ注解
一、execution实现AOP
1、创建Aspect
1 package lut.aop; 2 3 import org.aspectj.lang.annotation.After; 4 import org.aspectj.lang.annotation.Before; 5 import org.aspectj.lang.annotation.Pointcut; 6 import org.springframework.stereotype.Component; 7 8 @org.aspectj.lang.annotation.Aspect 9 @Component 10 public class Aspect { 11 12 @Pointcut("execution(* lut.aop.*.*(..))") 13 public void pointcut(){} 14 @Before("pointcut()") 15 public void print1(){ 16 System.out.println("befor process execute"); 17 } 18 19 @After("pointcut()") 20 public void print2(){ 21 System.out.println("after process execute"); 22 } 23 }
2、使用request调用
@RequestMapping("he") public String getMapp(){ System.out.println("mapping method execute"); return "kello"; }
结果:
befor process execute
mapping method execute
after process execute
二、使用特定注解来实现
1、创建特定注解
1 package lut.aop; 2 3 import java.lang.annotation.ElementType; 4 import java.lang.annotation.Retention; 5 import java.lang.annotation.RetentionPolicy; 6 import java.lang.annotation.Target; 7 8 @Target(ElementType.METHOD) 9 @Retention(RetentionPolicy.RUNTIME) 10 public @interface Print { 11 String value() default ""; 12 }
2、创建ASpect
1 package lut.aop; 2 3 import org.aspectj.lang.annotation.*; 4 import org.aspectj.lang.annotation.Aspect; 5 import org.springframework.stereotype.Component; 6 7 @Aspect 8 @Component 9 public class AnnotationAspect { 10 11 @Pointcut("@annotation(print)") 12 public void annotationpointcut(Print print){} 13 14 @Before("annotationpointcut(print)") 15 public void print1(Print print){ 16 System.out.println("befor process execute1"); 17 } 18 19 @After("annotationpointcut(print)") 20 public void print2(Print print){ 21 System.out.println("after process execute1"); 22 } 23 24 }
3、request调用
1 @Print 2 @RequestMapping("he1") 3 public String getMapp1(){ 4 System.out.println("mapping method execute1"); 5 return "kello"; 6 }
结果:
befor process execute1
mapping method execute1
after process execute1
三、若两种都实现,打印结果是什么?
befor process execute1 --注解方式
befor process execute --execution方式
mapping method execute1
after process execute --execution方式
after process execute1 --注解方式
注:就像栈一样
execution表达式意义:@Pointcut("execution(* lut.aop.*.*(..))")
方法参数可以设置为:(String,int)或者(String,*)或者(String,..).