gpt4 book ai didi

java - @Aspect 类,其建议签名类似于切入点表达式

转载 作者:行者123 更新时间:2023-12-02 11:42:53 27 4
gpt4 key购买 nike

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

所有类都在包com.springPointcut定义@AfterReturning Advice 的类型对于任何包类中的任何方法 com.spring具有任意数量的参数

spring.xml is well defined, in my classpath and the provided code is running

所以我的问题是,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));
}

}

我得到的输出是建议结果:5 In After Advice Result=5

最佳答案

根据 Spring 的 AOP 文档 here -

In Spring AOP, it is not possible to have aspects themselves be the target of advice from other aspects. The @Aspect annotation on a class marks it as an aspect, and hence excludes it from auto-proxying.

标记为@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]

关于java - @Aspect 类,其建议签名类似于切入点表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48417562/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com