Spring Boot Aop

一、添加依赖

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

二、创建service类

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

三、创建切面

@Component
@Aspect
public class AopLogAspect {
    @Pointcut("execution(* com.kxg.springboot.service.*.*(..))")
    public void pc1()
    {

    }

    @Before(value="pc1()")
    public void before(JoinPoint joinPoint)
    {
        String name = joinPoint.getSignature().getName();
        System.out.println(name + "方法开始执行...");
    }
    @After(value = "pc1()")
    public void  after(JoinPoint joinPoint)
    {
        String name = joinPoint.getSignature().getName();
        System.out.println(name + "方法执行结束...");
    }
    @AfterReturning(value="pc1()",returning = "result")
    public  void afterReturning(JoinPoint joinPoint,Object result)
    {
        String name = joinPoint.getSignature().getName();
        System.out.println(name + "方法返回值为:" + result);
    }

    @AfterThrowing(value = "pc1()",throwing = "e")
    public void  afterThrowing(JoinPoint joinPoint,Exception e)
    {
        String name = joinPoint.getSignature().getName();
        System.out.println(name + "方法抛出异常了,异常是" + e.getMessage());
    }

    @Around("pc1()")
    public  Object around(ProceedingJoinPoint pjp) throws Throwable{
        return pjp.proceed();
    }
}

1. @Pointcut("execution(* com.kxg.springboot.service.*.*(..))") 

        PointCut定义切入点

        第一个* 表示返回任意值

        第二个*表示service包下的任意类

        第三个*表示类中的任意方法

        括号中的两个 点表示方法参数 任意

        排除写法&& !execution(public * com.kxg.springboot.service.*(..))"

2.@Around 环绕通知,可以实现前置通知、后置通知、异常通知以及 返回通知的功能,目标方法进入环绕通知后,通过 调用ProceedingJoinPoint对象的proceed方法使目标方法继续执行,可以在这里修改目标参数、返回值等,并且可以在此处理目标方法的异常

四、在Controller创建接口

@RestController
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/getUserById")
    public String getUserById(Integer id)
    {
        return userService.getUserById(id);
    }
    @GetMapping("/deleteUserById")
    public  void deleteUserById(Integer id)
    {
         userService.deleteUserById(id);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值