gpt4 book ai didi

java - 对于单线程和多线程程序,在 aop 中编写切面的最佳实践是什么?

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

我的aop配置如下

aop:config>
<aop:aspect id="Intercepter" ref="aspect1">
<aop:around pointcut="execution(* *..*ServiceImpl.*(..))"
method="serviceIntercept" />

</aop:aspect>
</aop:config>

<bean id="aspect1" class=Intercepter">

</bean>

public class Intercepter

{
private String variable1;

public Intercepter()
{
}

public Object serviceIntercept(ProceedingJoinPoint pjp)
throws Throwable
{
Object retVal = null;
//Method M1 set value of variable1
M1();
// call actual Method on ServiceImpl
retVal = pjp.proceed();
}

public class AServiceImpl {
Method1();
Method1(){
call Method2 on BServiceImpl from AServiceImpl
BServiceImpl.Method2()
}

}

public class BServiceImpl {
Method2();

}

Main(){
// call AServiceImpl assuming it is single threaded.
AServiceImpl()


}

所以顺序如下

1.首先从Main()调用AServiceImpl(),它被拦截,变量variable1被设置为variable1="test";2.现在调用AServiceImpl上的实际方法Method1()。

3.从Method1()再次调用BServiceImpl上的Method2()。因此再次被拦截。之前variable1的值被设置为“test”,现在它被设置为“”。所以每次都会被拦截变量1的值改变了

那么,编写 aop 的最佳实践是什么,才能使其免受多线程和单线程程序的影响?

。在这种情况下,它是单例的,因为类 Intercepter 是单例和单线程的。所以我可以看到将方面编写为单例的问题。类似地,在多线程程序中也可能会出现类似的问题。可能会将方面类编写为不可变类或替换在我的理解中,具有原型(prototype)的单例可以是解决方案。但是,我想获得更深入的想法、信息以及人们在程序中使用的不同方法的解决方案。

最佳答案

在多线程程序中保持单例状态的最简单方法是使用 ThreadLocal变量。

就您而言,您必须替换 String variable1ThreadLocal<String> variable1 .

当使用ThreadLocal时,当该值不再使用时,您必须注意清除该值。一个好地方往往是finally子句,如:

try {
variable1.set(...)
pjp.proceed();
} finally {
variable1.remove();
}

关于java - 对于单线程和多线程程序,在 aop 中编写切面的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17311872/

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