Spring AOP:如何从方面从URI模板读取路径变量值?

我想创建Spring方面,该方面将通过自定义注释注释的方法参数设置为URI模板中的ID标识的特定类的实例。路径变量名称是注释的参数。与Spring非常相似@PathVariable

因此该控制器方法如下所示:

@RestController

@RequestMapping("/testController")

public class TestController {

@RequestMapping(value = "/order/{orderId}/delete", method = RequestMethod.GET)

public ResponseEntity<?> doSomething(

@GetOrder("orderId") Order order) {

// do something with order

}

}

代替经典:

@RestController

@RequestMapping("/testController")

public class TestController {

@RequestMapping(value = "/order/{orderId}/delete", method = RequestMethod.GET)

public ResponseEntity<?> doSomething(

@PathVariable("orderId") Long orderId) {

Order order = orderRepository.findById(orderId);

// do something with order

}

}

注释来源:

// Annotation

@Target(ElementType.PARAMETER)

@Retention(RetentionPolicy.RUNTIME)

public @interface GetOrder{

String value() default "";

}

方面来源:

// Aspect controlled by the annotation

@Aspect

@Component

public class GetOrderAspect {

@Around( // Assume the setOrder method is called around controller method )

public Object setOrder(ProceedingJoinPoint jp) throws Throwable{

MethodSignature signature = (MethodSignature) jp.getSignature();

@SuppressWarnings("rawtypes")

Class[] types = signature.getParameterTypes();

Method method = signature.getMethod();

Annotation[][] annotations = method.getParameterAnnotations();

Object[] values = jp.getArgs();

for (int parameter = 0; parameter < types.length; parameter++) {

Annotation[] parameterAnnotations = annotations[parameter];

if (parameterAnnotations == null) continue;

for (Annotation annotation: parameterAnnotations) {

// Annotation is instance of @GetOrder

if (annotation instanceof GetOrder) {

String pathVariable = (GetOrder)annotation.value();

// How to read actual path variable value from URI template?

// In this example case {orderId} from /testController/order/{orderId}/delete

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder

.currentRequestAttributes()).getRequest();

????? // Now what?

}

} // for each annotation

} // for each parameter

return jp.proceed();

}

}

谢谢!

回答:

如果您已经可以访问HttpServletRequest,则可以使用HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTEspring模板来选择请求中所有属性的映射。您可以这样使用它:

request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE)

结果是一个Map实例(不幸的是,您需要将其强制转换为实例),因此您可以对其进行迭代并获取所需的所有参数。

以上是 Spring AOP:如何从方面从URI模板读取路径变量值? 的全部内容, 来源链接: utcz.com/qa/423630.html

回到顶部