Java 在aop中为单线程和多线程程序编写方面的最佳实践是什么?

Java 在aop中为单线程和多线程程序编写方面的最佳实践是什么?,java,multithreading,spring,aop,spring-aop,Java,Multithreading,Spring,Aop,Spring Aop,我有如下aop配置 aop:config> <aop:aspect id="Intercepter" ref="aspect1"> <aop:around pointcut="execution(* *..*ServiceImpl.*(..))" method="serviceIntercept" /> </aop:aspect> </aop:conf

我有如下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() 


}
aop:config>

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

在您的情况下,必须将
stringvariable1
替换为
threadlocalvariable1

使用
ThreadLocal
时,必须注意在不再使用时清除该值。好地方通常是
finally
子句,如:

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