spring 中aop 切面实践

Posted 山阴路的秋天

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring 中aop 切面实践相关的知识,希望对你有一定的参考价值。

切面相关注解:

@Aspect : 声明该类为一个注解类

@Pointcut : 定义一个切点

@Before : 在切点之前执行

@After : 在切点之后执行 不管目标方法是否执行成功

@AfterReturning : 切点返回内容后执行代码,可以对切点的返回值进行封装

@AfterThrowing : 切点抛出异常后执行

@Around : 环绕,在切点前后执行代

 

1.自定义注解:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface timingAnnotation {
}

2.切面类

@Aspect
@Component
@Slf4j
public class AspectDemo {

    @Pointcut("@annotation(com.wl.demo.demos.aop.timingAnnotation)")
    public void pointCut() {
    }

    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("IP: {}", request.getRemoteAddr());
        log.info("URL: {}", request.getRequestURL().toString());
        log.info("HTTP Method: {}", request.getMethod());
        log.info("Class Method: {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
    }

    @Around("pointCut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        Object proceed = proceedingJoinPoint.proceed();
        long endTime = System.currentTimeMillis();
        log.info("[方法耗时]" + methodSignature.getDeclaringTypeName() + "." + methodSignature.getMethod().getName() + " 耗时: " + (endTime - startTime) + "毫秒");
        return proceed;
    }


    @After("pointCut()")
    public void doAfter(JoinPoint joinPoint) {
        log.info("目标方法执行完之后执行");
    }

    @AfterThrowing(pointcut = "pointCut()", throwing = "e")
    public void doAfterThrow(JoinPoint joinPoint, RuntimeException e) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("HTTP Method: {}", request.getMethod());
        log.info("Class Method: {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
    }

}

注:引入aspect 需要引入jar:

<!--引入aop aspectj-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
</dependency>

  

 

以上是关于spring 中aop 切面实践的主要内容,如果未能解决你的问题,请参考以下文章

Spring企业级程序设计 • 第3章 面向切面编程

Spring-AOP之工作实践

Spring的AOP面向切面编程

如何理解spring中的切面和过滤

Spring总结 3.AOP(xml)

Spring的AOP面向切面编程