Spring 当一个方法被AOP代理包装时,RequestContextHolder.currentRequestAttributes()将丢失其头
SpringAOP和请求上下文有一个奇怪的问题。我们在逻辑中使用RequestContextHolder.currentRequestAttributes()中的一些值。代理函数中的调用可以访问我们的属性。但是,当此函数返回时,将丢失请求属性,特别是请求头。我们无法确定原因,有点不知所措 有没有其他人遇到过这个问题,或者对如何修复这个bug有什么建议 实施细节Spring 当一个方法被AOP代理包装时,RequestContextHolder.currentRequestAttributes()将丢失其头,spring,spring-mvc,kotlin,spring-aop,Spring,Spring Mvc,Kotlin,Spring Aop,SpringAOP和请求上下文有一个奇怪的问题。我们在逻辑中使用RequestContextHolder.currentRequestAttributes()中的一些值。代理函数中的调用可以访问我们的属性。但是,当此函数返回时,将丢失请求属性,特别是请求头。我们无法确定原因,有点不知所措 有没有其他人遇到过这个问题,或者对如何修复这个bug有什么建议 实施细节 SpringBoot版本2.2.1.0发布 Kotlin版本1.3.60 我们已经实现了一个SpringAop代理来处理一个横切关注
- SpringBoot版本2.2.1.0发布
- Kotlin版本1.3.60
@Aspect
@Component
class OurAspect {
@AfterThrowing(value = "@annotation(annotation)", throwing = "ex", argNames = "ex,annotation")
fun handleExceptions(joinPoint: JoinPoint, ex: RuntimeException, annotation: AopAnnotation): Any {
throw SomeError()
}
}
这在Service1中使用
@Service
class Service1() {
@AopAnnotation
fun doStuff(): Any {
// RequestContextHolder.currentRequestAttributes has all requested properties here
return // business logic
}
}
在服务2中,我们称之为服务1
@Service
class Service2(private val service: Service1) {
fun doStuff(): Any {
val beforeRequest = getHeader() // this works
val result = service.doStuff()
val afterRequest = getHeader() // now missing
}
fun getHeader(): String {
val request = (RequestContextHolder.currentRequestAttributes() as ServletRequestAttributes).request
return request.getAttribute("header_name")
}
}