切面interview

131 阅读1分钟

切面AOP SpringBoot实现切面的步骤

  1. 引入依赖
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
  <version>2.6.1</version>
</dependency>
  1. 创建切面类,如LogAspect,并添加注解@Aspect,@Component
@Component
@Aspect
public class LogAspect {

}
  1. 设置切入点
/**
 * 切入点--》及切点表达式
* execution(public * *(..)) 任意的公共方法
* execution(* set*(..)) 以set开头的所有的方法
* execution(* com.LoggerApply.*(..))com.LoggerApply这个类里的所有的方法
* execution(* com.annotation.*.*(..))com.annotation包下的所有的类的所有的方法
* execution(* com.annotation..*.*(..))com.annotation包及子包下所有的类的所有的方法
* execution(* com.annotation..*.*(String,?,Long)) com.annotation包及子包下所有的类的有三个参数,第一个参数为String类型,第二个参数为任意类型,第三个参数为Long类型的方法
* execution(@annotation(com.lingyejun.annotation.Lingyejun))
 */
@Pointcut(value = "execution(* com.lingluo.base.controller.AlipayFlowController.findById(*))")
public void logPointCut(){

}

4.设置通知

// @Around(value = "logPointCut()") 等价 ↓
@Around(value = "execution(* com.lingluo.base.controller.AlipayFlowController.findById(..))")
public Object around(ProceedingJoinPoint point) {
    logger.info("11111111111111111111111111111");
    return null;
}

切面是由动态代理实现

与业务相关不大的抽取出来,

什么叫切面,什么是面向切面编程

Spring中使用切面的步骤 切面用在什么地方 日志,权限,数据库链接

要素描述
切面Aspect标识Aspect接口的类
切点PointCut什么地方?切点中存在切点表达式,在那个类,那个方法切入
连接点JoinPoint什么时候切入?如方法调用之前,发生异常之后等
织入什么时候引入?将切面切入到方法,是方法得到增强的过程,叫织入
引入
增强Advice
目标类Target被一个或多个切面通知的对象
五大通知类型
环绕通知Around
前置通知Before
后置通知After
结束通知AfterReturn
异常通知AfterThrow