基于@Aspect的Spring AOP实现竟然没有运行:Spring“最直觉”的调试思路

摘要
本文通过一个问题“基于@Aspect的Spring AOP实现竟然没有运行”的调试全过程,给出了Spring最基础最“直觉”最“特别”的调试思路:考虑对象是否被框架加载/实例化了?


比较了解Spring AOP的同学可以直接看第二部分“2. 调试思路总结”。阅读本文大概需要10min。

1. 基于@Aspect的Spring AOP实现为什么没有运行

1.1 基于@Aspect的Spring AOP实现代码

这是一个用IntelliJ IDEA开发的使用Maven搭建Spring Boot应用。
在这里插入图片描述

AnnotationApplication.java的源码:

package com.aop.annotation;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Arrays;

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

Operation.java是AOP的目标对象,即符合PointCut所指定的条件,被AOP织入横切逻辑(Advice)的对象。

package com.aop.annotation;

import org.springframework.stereotype.Component;

@Component
public class Operation {
   
    public int add(int operand1, int operand2) throws Exception {
   
        System.out.println("add operation.");
        int result = operand1 + operand2;
        if (result < 10) {
   
            throw new Exception("not valid result.");
        } else {
   
            System.out.println("The result is: " + result);
            return result;
        }
    }

    public void show() {
   
        System.out.println("function show().");
    }
}

BeforeAdvice.java 是定义了Before Advice的Aspect对象。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值