【问题标题】:@Aspect class with an advice signature similar to pointcut expression具有类似于切入点表达式的建议签名的 @Aspect 类
【发布时间】:2018-01-24 17:58:23
【问题描述】:

我在学习 AOP 时遇到了一个场景。

所有类都在包com.spring中 而Pointcut 定义了@AfterReturning 类型的Advice 对于任何类的包com.spring 中的任何方法,带有任意数量的参数

spring.xml 定义明确,在我的类路径中并且提供的代码正在运行

所以我的问题是,Aspects 类的这个建议不应该无限运行,因为它本身满足 Pointcut 定义吗?

这是我的方面类

package com.spring;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class Aspects {

    @AfterReturning(pointcut = "execution(* com.spring.*.*(..))", returning= "res")
    public void logAfterExecutionAdvice(int res){
        System.out.print("Result in advice: "+res);
         System.out.print(" In After Advice ");
  }
}

我的加法器类

package com.spring;

public class Adder {
    private int a;
    private int b;
    public int add(int a,int b){
       return (a+b);
    }
    /**
     * @return the a
     */
    public int getA() {
        return a;
    }
    /**
     * @param a the a to set
     */
    public void setA(int a) {
        this.a = a;
    }
    /**
     * @return the b
     */
    public int getB() {
        return b;
    }
    /**
     * @param b the b to set
     */
    public void setB(int b) {
        this.b = b;
    }
}

还有我的主类

package com.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {
    ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
    Adder adder=(Adder)ctx.getBean("adder");
    System.out.print("Result=" + adder.add(2,3));
    }

}

我得到的输出是 Result in advice: 5 In After Advice Result=5

【问题讨论】:

  • 不,因为你的方面方法执行,但实际上并没有返回任何东西。
  • 这是因为通知仅在 spring bean 上调用该方法时执行,在您的情况下 Adder bean 由 spring 维护,因此它仅适用于该 bean 的方法。
  • 是不是@Aspect注解类中的所有方法都被切入点表达式排除在外?
  • @ShabbirEssaji 没错!!
  • 如果你绝对想从其他切面中截取切面,你需要配置你的应用程序使用AspectJ而不是Spring AOP。那么就没有问题了。

标签: java spring aop aspectj spring-aop


【解决方案1】:

根据 Spring 的 AOP 文档 here -

在 Spring AOP 中,切面本身是不可能的 其他方面的建议目标。类上的@Aspect 注解 将其标记为方面,因此将其排除在自动代理之外。

标记为@Aspect 的类被排除在自动代理和切入点之外。

所以,如果你尝试这样的事情 -

package com.spring;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class Aspects {
    @After("execution(* com.spring.Aspects.*(..))")
    public void logAfterExecutionAdvice(){
        System.out.print("In After Advice ");
    }
}

Spring 会给出类似的错误 -

Error:(12, 0) ajc: advice defined in com.spring.Aspects has not been applied [Xlint:adviceDidNotMatch]

【讨论】:

  • 哦..太好了!!我没有首先阅读文档,但假设这样的事情可能是答案。谢谢!
猜你喜欢
  • 2023-04-08
  • 2012-12-22
  • 2015-12-16
  • 2015-12-06
  • 2012-07-19
  • 1970-01-01
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多