gpt4 book ai didi

spring - 如何使 @Controller 映射路径可配置?

转载 作者:行者123 更新时间:2023-12-02 00:34:10 25 4
gpt4 key购买 nike

我正在构建一个内部库,它应该自动向 Spring MVC 应用程序添加一些 Controller 。这些 Controller 都是@RestController,带有一些用@RequestMapping注释的处理程序方法。由于它是一个库,我希望用户能够指定库应公开所有这些 Controller 的根路径。插图:

// given that I have a controller like this:
@RestController
@RequestMapping("/admin")
class AdminController {
@RequestMapping("/users")
UsersDto allUsers() { ... }
}

// it will be exposed at `http://localhost/admin/users`

我想要实现的是使 /admin 部分可配置。例如,如果用户在 application.properties 中说:

super.admin.path=/top/secret/location/here

我希望 AdminController 的处理程序可以在 http://localhost/top/secret/location/here 上使用,因此 allUsers() 处理程序应具有完整路径:

http://localhost/top/secret/location/here/users

我该如何实现这一目标?感觉像是一个非常常见的任务,但我没有找到一个有效的简单解决方案。

我的发现#1

有一个 SimpleUrlHandlerMapping 机制似乎正是我想要的:

@Bean
public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
simpleUrlHandlerMapping.setOrder(Integer.MAX_VALUE - 2);
simpleUrlHandlerMapping.setUrlMap(Collections.singletonMap("/ANY_CUSTOM_VALUE_HERE/*", "adminController"));
return simpleUrlHandlerMapping;
}

但它一直说

The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler

我的发现#2

Spring Boot Admin 项目具有此功能 - 您可以配置它们应在何处公开其所有端点。他们似乎在 PrefixHandlerMapping 中从头开始实现了此功能。 。他们如何使用它:

...
@Bean
public PrefixHandlerMapping prefixHandlerMappingNotificationFilterController() {
PrefixHandlerMapping prefixHandlerMapping = new PrefixHandlerMapping(notificationFilterController());
prefixHandlerMapping.setPrefix(adminServerProperties.getContextPath());
return prefixHandlerMapping;
}
...

最佳答案

除了@M。 Deinum 解决方案,您可以使用带有占位符的路径模式。如Spring documentation状态:

Patterns in @RequestMapping annotations support ${…​} placeholders against local properties and/or system properties and environment variables. This may be useful in cases where the path a controller is mapped to may need to be customized through configuration.

所以在你的情况下,你的 Controller 会是这样的:

@RestController
@RequestMapping("/${super.admin.path:admin}")
class AdminController {
// Same as before
}

前面的 Controller 将使用 super.admin.path 本地/系统属性或环境变量值作为其前缀,或者使用 admin (如果未提供)。如果您使用的是 Spring Boot,请将以下内容添加到 application.properties 中:

super.admin.path=whatever

您可以自定义该前缀。

关于spring - 如何使 @Controller 映射路径可配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37513117/

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