gpt4 book ai didi

java - 调用方法时未给出预期结果

转载 作者:行者123 更新时间:2023-12-02 09:36:02 26 4
gpt4 key购买 nike

我正在开发 spring 应用程序,我想在类中调用任何 setxx(..) 方法时触发方面 @Before。当执行 Details 类时,SetterInterceptor @Before 方面不会被执行叫。

我有以下类(class):

package com.mypack;
public class Person {
private String id;
private String firstName;
private String lastName;

public String getId() { return id; }
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }

public void setId(String id) { this.id = id; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public String toString() { return "Person[" + id + ",
+ firstName + ", " + lastName+ "]"; }
}

详细信息类:

package com.mypack;
public class Details extends Person{

private String address;
private String contactNum;
//getters and setters
public String toString() { return "Details[" + address + ",
" + contactNum+ "]"; }

public static void main(String[] args) {
Details obj1 = new Details();
obj1.setAddress("xx 202");
obj1.setContactNum("2124551234");
obj1.setId("242");
obj1.setFirstName("John");
obj1.setLastName("John");

Details obj2 = new Details();
obj2.setAddress("ASDf 202");
obj2.setContactNum("234544565656");
obj2.setId("23689");
obj2.setFirstName("Sam");
obj2.setLastName("S");

System.out.println("obj1 : " + obj1);
System.out.println("obj2 : " + obj2);

obj2.setFirstName("Samuel");
}

}

SetterInterceptor类:

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class SetterInterceptor {
@Before("execution(* com.mypack.Details.set*(*))")
public void before(JoinPoint joinPoint) throws Throwable {
Object[] signatureArgs = joinPoint.getArgs();
for (Object signatureArg : signatureArgs) {
Person obj = (Person) signatureArg;
System.out.println("Before : " + obj.getFirstName() + " ---- "
+ obj.getId());

}

}
}

任何输入都会有帮助。

最佳答案

来自 Spring AOP 的文档(重点是我的):

Spring AOP currently supports only method execution join points (advising the execution of methods on Spring beans)

换句话说,您想要拦截的任何方法调用都需要位于由 Spring 实例化的 bean 上。

在您的示例中,应用程序甚至不是 Spring 应用程序(您没有 ApplicationContext),并且您使用 new 创建 Details 实例。

关于java - 调用方法时未给出预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57512645/

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