AOP 入门案例

  • AOP 概念:AOP

一、配置 Pom 坐标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependencies>
<!-- spring-context 内置了 spring-aop 包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.13.RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.14</version>
</dependency>
</dependencies>

二、Service 层实现

UserService

1
2
3
4
public interface UserService {
void save();
void update();
}

UserServiceImpl

1
2
3
4
5
6
7
8
9
10
@Service
public class UserServiceImpl implements UserService {
public void save(){
System.out.println("User Service Save ...");
}

public void update(){
System.out.println("User Service Update ...");
}
}

三、AOP 层实现

  • 在 AOP 类中加入 @Aspect 声明这是一个 切面
  • 使用 @Pointcut 声明一个切入点
    • 切入点定义依托一个不具有实际意义的方法进行,即无参、无返回值,方法体无实际逻辑。
  • 使用 @Before 声明通知类型,并且绑定切入点
    • 绑定切入点与通知关系,并指定通知添加到原始连接点的具体执行位置

/aop/MyAdvice

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 声明这是一个 bean
@Component
// 声明这是 AOP 类
@Aspect
public class MyAdvice {
// 创建切入点
@Pointcut("execution(void cn.pangcy.service.impl.UserServiceImpl.save())")
private void pt(){

}

// 创建通知
@Before("pt()")
public void method(){
System.out.println(System.currentTimeMillis());
}
}

四、SpringConfig

  • 给 SpringConfig 配置 @EnableAspectJAutoProxy :使用注解开发 AOP。
1
2
3
4
5
6
@Configuration
@ComponentScan("cn.pangcy")
// 启用 AscoectJ 自动代理
@EnableAspectJAutoProxy
public class SpringConfig {
}

AOP 入门案例
https://blog.pangcy.cn/2023/04/09/后端编程相关/java/spring/AOP 入门案例/
作者
子洋
发布于
2023年4月9日
许可协议