SpringBoot中AOP的如何使用?

SpringBoot中AOP的如何使用?

1、准备多个Controller

package com.base.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class HelloController {

    @RequestMapping("/hello")
    public String hello() {
       log.info("hello");
        return "hello";
    }

}
package com.base.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class TestController {

    @RequestMapping("/test")
    public String hello() {
        log.info("test");
        return "test";
    }

}

2、引入jar

<!--aop 切面-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

3、定义切点与通知

package com.base.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 定义切点与通知
 */
@Aspect
@Component
@Slf4j
public class AopConfig {
    /**
     * 切点
     */
    @Pointcut("execution (* com.base.controller.*.*(..))")
    public void helloWorld() {

    }

    /**
     * 通知
     */
    @Before("helloWorld()")
    public void beforeAdvice() {//前置通知
        log.info("...beforeAdvice...");
    }

    @After("helloWorld()")
    public void afterAdvice() {//后置通知
        log.info("...afterAdvice...");
    }

    @Around("helloWorld()")
    public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {//环绕通知
        log.info("...aroundBeforeAdvice...");
        proceedingJoinPoint.proceed();
        log.info("...aroundAfterAdvice...");
    }

}

4、测试

http://localhost:8001/hello
在这里插入图片描述

http://localhost:8001/test
在这里插入图片描述

5、解释@Pointcut(“execution (* com.base.controller..(…))”)含义

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值