【问题标题】:Spring Boot AOP nested custom annotations not called [duplicate]未调用 Spring Boot AOP 嵌套自定义注释
【发布时间】:2023-01-27 22:14:02
【问题描述】:

我在 Spring Boot 中创建了一个简单的自定义注解,它记录了一些东西并且它正在工作但仅适用于第一个注解,嵌套的注解不会被调用

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Traceable {

}

注释处理器(方面)

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class TraceableAspect {

    @Around("@annotation(Traceable)")
    public Object trace(ProceedingJoinPoint joinPoint) throws Throwable {

        System.out.println("Inside Aspect");
        
        Object result = joinPoint.proceed();

        System.out.println(result);
        return result;
    }
}

用于测试的控制器示例

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/test")
public class ControllerTest {

    @GetMapping("/get")
    @Traceable
    public String get(){

        test1();
        test2();

        return "Hi";
    }
    
    @Traceable
    public void test1(){
        String str = "1";
        System.out.println(str);
    }

    @Traceable
    public Object test2(){
        String str = "2";
        System.out.println(str);

        test1();
        return null;
    }

}

这里的控制台输出是:

Inside Aspect
1
2
1
Hi

但我认为它很糟糕,它必须是这样的:

    Inside Aspect
    Inside Aspect
    1
    Inside Aspect
    2
    Inside Aspect
    1
    Hi

似乎只处理了第一个@Traceable,其他的都被忽略了。如何处理?谢谢

【问题讨论】:

    标签: java spring-boot annotations aop


    【解决方案1】:

    要了解为什么会得到您所看到的结果,您必须了解 Spring 如何实现对大多数行为注释的处理:使用代理。这意味着只有通过代理的方法调用才能获得注释行为。这是一个典型的场景,当一个对象调用它对另一个对象的引用时;该引用实际上是对代理的引用,它拦截调用并将行为(在本例中为日志记录)包装在调用周围。但是,当在同一个实例中调用方法时,没有代理在起作用(Spring 不会/不能用对代理的引用替换 this),因此没有注释行为。

    有几种方法可以解决这个问题,this SO Q&A 中讨论了一些想法。 There are also some answers here 具有解决代理限制的选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2018-10-15
      • 2016-06-08
      • 2017-12-26
      • 1970-01-01
      相关资源
      最近更新 更多