要解决这个问题,可以使用ThreadLocal来存储AOP中创建的属性。代码示例如下:
public class AopAspect {
private ThreadLocal myAttribute = new ThreadLocal<>();
@Before("execution(* com.example.service.SomeService.doSomething(..))")
public void beforeDoSomething() {
myAttribute.set("AopAspect");
}
@AfterReturning(value = "execution(* com.example.service.SomeService.doSomething(..))", returning = "returnValue")
public void afterReturnFromDoSomething(Object returnValue) {
String myAttributeValue = myAttribute.get();
// do something with myAttributeValue
myAttribute.remove();
}
}
@Service
public class SomeService {
@Autowired
private HttpServletRequest request;
public void doSomething() {
String requestAttributeValue = (String) request.getAttribute("myAttribute");
// requestAttributeValue is null
}
}
在上面的代码片段中,我们使用ThreadLocal来存储AOP中创建的属性。在beforeDoSomething()方法中,我们将属性的值设置为"AopAspect"。在afterReturnFromDoSomething()方法中,我们可以从ThreadLocal中获取AOP创建的属性值,并进一步进行处理。通过这种方式,我们可以解决通过@RequestAttribute获取AOP创建的自己的属性值为null的问题。
上一篇:AOP操作中针对属于不同子包下的类中的方法进行切点表达式的设置
下一篇:AopConfigException:CouldnotgenerateCGLIBsubclassofclasserroroncreatingtheinstanceofmykotlindataclass