gpt4 book ai didi

spring - 以编程方式控制 @RestController 可用性

转载 作者:行者123 更新时间:2023-12-02 02:35:08 26 4
gpt4 key购买 nike

是否可以通过编程方式控制@RestController来启用或禁用它?我不想只在每个 @RequestMapping 方法中编写代码来执行某种 if (!enabled) { return 404Exception; } }

我见过this question但这仅在启动时有效。我真正需要的是允许我多次启用或禁用 Controller 的东西。

我想过不同的方法,但不知道哪些方法在 Spring 可行。

  1. 实际控制容器(在我的例子中是jetty),以便禁用对该特定端点的请求
  2. 以某种方式控制RequestMappingHandlerMapping,因为它似乎是在 url 和 Controller 之间进行映射的类
  3. 控制@RestController组件的生命周期,以便我可以随意创建和销毁它,但我不确定如何触发到端点的映射

最佳答案

如果最终结果是当您决定应禁用特定端点时希望以 404 响应,那么您可以编写一个拦截器来检查您的启用条件是否为 false,如果是,则相应地设置响应。

例如:

@Component
public class ConditionalRejectionInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
String requestUri = request.getRequestURI();
if (shouldReject(requestUri)) {
response.setStatus(HttpStatus.NOT_FOUND.value());
return false;
}
return super.preHandle(request, response, handler);
}

private boolean shouldReject(String requestUri) {
// presumably you have some mechanism of inferring or discovering whether
// the endpoint represented by requestUri should be allowed or disallowed
return ...;
}
}

在 Spring Boot 中,注册自己的拦截器只需要实现一个 WebMvcConfigurerAdapter。例如:

@Configuration
public class CustomWebMvcConfigurer extends WebMvcConfigurerAdapter {

@Autowired
private HandlerInterceptor conditionalRejectionInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
// you can use .addPathPatterns(...) here to limit this interceptor to specific endpoints
// this could be used to replace any 'conditional on the value of requestUri' code in the interceptor
registry.addInterceptor(conditionalRejectionInterceptor);
}
}

关于spring - 以编程方式控制 @RestController 可用性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45829696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com