问题描述
各种 @RequestMapping
方法具有要在运行时进行分析的自定义注释.
Various @RequestMapping
methods inside my @Controller
classes have custom annotations that I want to analyze at runtime.
例如:
@Controller
@RequestMapping("/bla")
@RequireCommunityLevel("...")
@AnotherCustomAnnotation(value = "...")
public class FakeController {
// ...
@RequireScore(level = Score.Platinum, score = 8500)
@RequestMapping("/blabla")
@AnotherCustomAnnotation(value = "...")
public DTOResponse<MySpecialModel> getMySpecialModels() {
// ...
}
}
当我在自定义的 Interceptor
和 Filter
类中收到请求时,我想分析该请求将调用哪个 Method
.
When I receive a request in my custom Interceptor
and Filter
classes, I want to analyze which Method
the request is going to call.
我过去使用基于 Javax Servlet
和 Jetty
的自定义框架,并且经常实现某种 method-registry 讯问.
I have worked in the past with custom frameworks based on Javax Servlet
and Jetty
and often implemented some kind of method-registry one could interrogate.
例如:
public class CustomFilter extends Filter {
@Inject
private MyMethodRegistry registry;
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// get the request path
final String path = getPath(request);
final Method m = this.registry.getMethodForPath(path);
// that's what I mean to do
if (m.getAnnotation(RequireScore.class) != null) { ... }
if (m.getDeclaringClass().getAnnotation(AnotherCustomAnnotation.class != null) { ... }
chain.doFilter(request, response);
}
}
我正在寻找 Spring
中的类似方法,这可能是一个内置实用程序,用于在运行时分析 @RequestMapping
方法.所有这些都应该在我的拦截器/过滤器中进行.
I'm looking for a similar way in Spring
, possibly a built-in utility to analyze at runtime the Annotation
's on my @RequestMapping
methods. All of this should happen within my Interceptor/Filter.
推荐答案
按照@ M.Deinum的建议,您可以在 Interceptor
中获取 Handler
作为参数.
As @M.Deinum advised in the comments you can get the Handler
as parameter in your Interceptor
.
我还找到了本教程完全解释了我所需要的.
I have also found this tutorial that explains exactly what I needed.
在 HandlerInterceptor :: preHandle
final HandlerMethod handlerMethod = (HandlerMethod) handler; // the last parameter
final Method method = handlerMethod.getMethod();
// check for annotations
这篇关于Spring-拦截器/过滤器中给定请求的get方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!