【发布时间】:2019-01-20 00:54:19
【问题描述】:
如何在 Spring/Spring boot 中使用 AOP 更新 header 参数并将其发送到 Controller?我可以添加但无法将其发送到控制器。我在控制器中得到空值。我不想使用@Around。
@Before("PointcutDefinition.controllerLayer()")
public Object beforeAdvice(JoinPoint joinPoint)
{
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
request.setAttribute("traceId", ServiceUtil.getTraceId());
return request;
}
更新:
我能够使用以下代码更新 traceId。
@Around("execution(* com.test.api.*.*(..)) && " + "args(traceId,..)")
public Object setTraceId(ProceedingJoinPoint joinPoint, String traceId) throws Throwable
{
String newTraceId = ServiceUtil.getTraceId();
Object result = joinPoint.proceed(new Object[]
{ newTraceId, "", "", "", "", "", "", "", "", "" });
return result;
}
在我的控制器中,我有多个方法,参数数量不同。但是所有方法中的第一个参数是traceId。我想单独更新 traceId 并保持其他参数不变。但在上述方法中,我不得不传递所有论点。有没有办法我可以单独更新第一个参数并发送其余参数不变。
【问题讨论】:
-
你要设置的是标题还是属性?
-
我的控制器类 -> public ResponseEntity
loginSession(@RequestHeader(value = "traceId", required = false) String traceId,...) 我想为 traceId 设置值。 -
你为什么不想使用@Around?
-
我很好使用@Around(如果这是实现这一目标的唯一方法)。我的印象是,只有当我们想在调用该方法之前和之后做某事时,我们才应该使用 Around。但就我而言,我想在调用方法之前而不是在调用方法之后做一些事情。
标签: spring spring-boot spring-mvc aop spring-aop