1.概要
AOP (Aspect Orient Programming),直译过来就是 面向切面编程。面向切面编程是一种编程范式,它作为OOP面向对象编程的一种补充,用于处理系统中分布于各个模块的横切关注点,比如事务管理、权限控制、缓存控制、日志打印等等。
2.相关概念
3.配置过程
3.1 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
3.2 创建需要被切入的方法demo,及注解(介绍两种方法进行aop切入,一个是根据注解,一个是根据方法名)
首先需要在main方法中添加以下注解
@EnableAspectJAutoProxy
创建自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
String name();
}
被拦截的方法
@Service
public class AspectjTest {
//通过注解拦截
@Action(name = "aop")
public String getAopTest(){
return "使用注解的切面被执行了!";
}
//通过方法名拦截
public void getAspectTest(){
System.out.println("使用方法的被拦截了!");
}
}
定义切面
@Component
@Aspect
public class AspectTestConfig {
@Pointcut("@annotation(com.rising3000.base.test.Action)")
public void annotationPointCut(){}
@After("annotationPointCut()")
public void after(JoinPoint point){
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
Action annotation = method.getAnnotation(Action.class);
System.out.println("注解方法的拦截after:"+annotation.name());
}
@After("execution( * com..*.getAspectTest(..))")
public void afterMethod(){
System.out.println("根据方法名拦截");
}
}