AOP实战-AspectJ


本文的出现是为了能够分享个人所学的相关知识,检验自身学习成果。内容会和其他技术存在部分关联,如有任何描述错误或者说明有误的地方,还望各位大佬指出。

1. 背景

用过Spring的都知道DI和AOP,今天介绍一个实现AOP超级且方便功能强大的框架AspectJ。此文默认读者有一定spring基础。

2. 环境

JDK:1.8

架构:SpringBoot

3. 详解

3.1 基础概念

Aspect:切面

Pointcut:切点,通过不同切入点,执行不同操作,此文中展示execution时机执行的操作。

Advice:通知,包括前置通知、后置通知、异常通知、环绕通知等等;其中,环绕通知功能最为强大。此文展示环绕通知用法。

3.2 AspectJ依赖:

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.5</version>
</dependency>

3.3 代码实现

step1:首先在SpringBoot配置类中添加注解@EnableAspectJAutoProxy,如下:

@EnableAspectJAutoProxy
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

step2:新建AspectjAop class,使用@Aspect标记为切面,注册到Spring容器中

@Slf4j
@Aspect
@Component
public class AspectjAop {
}

step3:新建方法controllerPointCut,添加Pointcut,切点时机为“execution”,匹配方法为controller报下所有public 方法。可以对请求进行信息安全过滤等等操作。

@Slf4j
@Aspect
@Component
public class AspectjAop {
    /**
     * 此路径表示controller下所有类中的public方法
     */
    @Pointcut("execution(public * com..controller..*(..))")
    private void controllerPointCut() {
    }
}

step4:添加Advice,注入执行中切点实例ProceedingJoinPoint,ProceedingJoinPoint可以获取入参,控制执行等等操作。可以在执行方法前后进行方法增强,实现业务等。

@Slf4j
@Aspect
@Component
public class AspectjAop {
    /**
     * 此路径表示controller下所有类中的public方法
     */
    @Pointcut("execution(public * com..controller..*(..))")
    private void controllerPointCut() {
    }

    @Around(value = "controllerPointCut()")
    private Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) {
        // TODO: Pre-operation
        log.info("You can check the parameters.");
        Object obj = null;
        try {
            obj = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            log.error("controller throwable");
        }
        // TODO:Post-operation
        log.info("You can encapsulate the return value.");
        return obj;
    }
}

 上一篇
SpringBoot-Build SpringBoot-Build
本文的出现是为了能够分享个人所学的相关知识,检验自身学习成果。内容会和其他技术存在部分关联,如有任何描述错误或者说明有误的地方,还望各位大佬指出。 1. 背景SpringBoot是微服务基础,此文讲述搭建SpringBoot方式。 2
2020-05-27
下一篇 
DistributedLock-Redis DistributedLock-Redis
本文的出现是为了能够分享个人所学的相关知识,检验自身学习成果。内容会和其他技术存在部分关联,如有任何描述错误或者说明有误的地方,还望各位大佬指出。 1. 背景在分布式项系统的大背景下,CAP中分区容错性是必不可少的。多节点的协调尤为重
2020-05-27
  目录