SpringBoot学习之AOP

新建UserService类

package org.hx.springboot_aop_demo24.service;

import org.springframework.stereotype.Service;

@Service
public class UserService {
    public String getUserById(Integer id){
        System.out.println("getUserById");
        return "user";
    }
    public void deleteUserById(Integer id){
        System.out.println("delete id: "+id);
    }
}

新建LogAspect类

package org.hx.springboot_aop_demo24;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class LogAspect {
    //切点
    @Pointcut("execution(* org.hx.springboot_aop_demo24.service.*.*(..))")
    public void pointMethod(){

    }
    //前置通知
    @Before("pointMethod()")
    public void before(JoinPoint joinPoint)
    {
        String name = joinPoint.getSignature().getName();
        System.out.println("方法开始执行了");
    }
    //后置通知
    @After("pointMethod()")
    public void after(JoinPoint joinPoint)
    {
        String name = joinPoint.getSignature().getName();
        System.out.println("方法执行结束了。。。");
    }
    //执行后的返回值
    @AfterReturning(value = "pointMethod()",returning = "s")
    public void afterReturning(JoinPoint joinPoint,String s){
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"方法返回值是: "+s);
    }
    //返回后抛出异常
    @AfterThrowing(value = "pointMethod()",throwing = "e")
    public void afterthrowing(JoinPoint joinPoint,Exception e)
    {
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"方法抛出了异常"+e.getMessage());
    }
    //环绕通知
    @Around("pointMethod()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint){
        try {
            //方法之前执行通知,相当于前置通知
            //类似反射中的invoke方法
            Object proceed = proceedingJoinPoint.proceed();
            //方法之后执行通知,相当于后置通知
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return  null;
    }
}

在单元测试类中进行测试

package org.hx.springboot_aop_demo24;

import org.hx.springboot_aop_demo24.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootAopDemo24ApplicationTests {

    @Autowired
    UserService userService;

    @Test
    void contextLoads() {
        userService.getUserById(99);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值