- AOP(Aspect Oriented Programming)面向切面编程
- 作用:在不惊动原始设计的基础上为其进行功能增强
一、AOP入门案例(在接口执行前输出当前系统时间)
1.导入坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
2.制作连接点方法
package com.wangpeng.dao.impl;
import com.wangpeng.dao.BookDao;
public class BookDaoImpl implements BookDao {
@Override
public void selectById() {
System.out.println("select");
}
@Override
public void update() {
System.out.println("update");
}
}
3.编写通知类,定义切入点以及绑定关系
package com.wangpeng.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class MyAdvice {
// 切入点 1
@Pointcut("execution(void com.wangpeng.dao.BookDao.selectById())")
private void pointCut1(){}
// 切入点 2
@Pointcut("execution(void com.wangpeng.dao.BookDao.update())")
private void pointCut2(){}
@Before("pointCut1()") // 绑定关系
// 共性方法
public void method() {
System.out.println(System.currentTimeMillis());
}
}
4.配置类添加注解 (@EnableAspectJAutoProxy)
package com.wangpeng.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan("com.wangpeng")
@EnableAspectJAutoProxy
public class SpringConfig {
}
5.编写测试方法并执行
package com.wangpeng;
import com.wangpeng.config.SpringConfig;
import com.wangpeng.dao.BookDao;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
@org.junit.Test
public void selectById(){
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
BookDao bean = annotationConfigApplicationContext.getBean(BookDao.class);
bean.selectById();
}
}
1675755982096
select
二、切入点表达式
- 切入点表达式:要进行增强的方法的描述方式
2.1 举例
描述方式一:执行com.wangpeng.dao包下BookDao接口的无返回值无参数的selectById方法
@Pointcut("execution(void com.wangpeng.dao.BookDao.selectById())")
描述方式二:执行com.wangpeng.dao.impl包下BookDaoImpl实现类的无返回值无参数的selectById方法
@Pointcut("execution(void com.wangpeng.dao.impl.BookDao.selectById())")
2.2 切入点标准格式
3.AOP通知类型
// 后置通知
@After("pointCut1()")
public void methodAfter() {
System.out.println("after advice...");
}
// 环绕通知
@Around("pointCut2()")
public void methodAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("before advice...");
Object proceed = pjp.proceed();
System.out.println("after advice...");
}