gpt4 book ai didi

java - Spring AOP执行顺序

转载 作者:太空宇宙 更新时间:2023-11-04 07:03:37 25 4
gpt4 key购买 nike

我是 Spring AOP 的新手,这是我的测试代码:

目标内部com.kk.entity封装:

@Component
public class AopTargetOne {
private String name;
private String password;
private String email;
private String address;

//getter and setters omitted
}

@Component
public class AopTargetSecond {
private String name;
private int age;
private String email;
//getter and setters omitted
}

方面:

@Component
@Aspect
public class VariableCheckAspect {

//intercept all the setter methods
@Pointcut("execution(* com.kk.entity.*.set*(..))")
private void aopIsSetMethod() {

}

@Before("com.kk.aop.VariableCheckAspect.aopIsSetMethod() && args(val,..)")
public void checkSetValue(JoinPoint joinpoint, String val) {
System.err.println("******** Start check set value with method *********** " + joinpoint.getSignature());
System.out.println("value is:" + val);
System.err.println("******** End ****");
}
}

应用:

    AopTargetOne ah = context.getBean(AopTargetOne.class);
ah.setAddress("aopholder address");
ah.setEmail("aopholder email");
ah.setName("aopholder name");

AopTargetSecond ak = (AopTargetSecond) context.getBean("aopTargetSecond");
ak.setName("aopkepper name");
ak.setEmail("aopkepper email");
ak.setAge(23);

我得到了输出:

******** Start check set value  with method *********** void com.kk.entity.AopTargetOne.setAddress(String)
******** End ****
value is:aopTargetOne address
******** Start check set value with method *********** void com.kk.entity.AopTargetOne.setEmail(String)
******** End ****
******** Start check set value with method *********** void com.kk.entity.AopTargetOne.setName(String)
******** End ****
******** Start check set value with method *********** void com.kk.entity.AopTargetTwo.setName(String)
******** End ****
value is:aopTargetOne email
value is:aopTargetOne name
value is:aopTargetTwo name
******** Start check set value with method *********** void com.kk.entity.AopTargetTwo.setEmail(String)
******** End ****
value is:aopTargetTwo email

这让我很困惑!看来代码没有按正常顺序运行。

虽然我期望这样的输出:

******** Start check set value  with method *********** void com.kk.entity.AopTargetOne.setAddress(String)
value is:aopTargetOne address
******** End ****
******** Start check set value with method *********** void com.kk.entity.AopTargetOne.setEmail(String)
value is:aopTargetOne email
******** End ****
....

有什么问题吗?有办法解决这个问题吗?

最佳答案

这只是您在两个不同的输出流上执行输出的结果。您正在写入 erroutThese don't necessarily get flushed in the same order (between streams).

System.err.println(..);
System.out.println(..);

写入相同的OutputStream,您将看到预期的输出。

如果我们删除包含星星的输出,我们会得到

value is:aopTargetOne address
value is:aopTargetOne email
value is:aopTargetOne name
value is:aopTargetTwo name
value is:aopTargetTwo email

这与您设置它们的顺序完全相同。

关于java - Spring AOP执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21746932/

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