我正在构建一个内部库,它应该自动向Spring MVC应用程序添加一些控制器.这些控制器都是@RestController,带有一些使用@RequestMapping注释的处理程序方法.由于它是一个库,我希望用户能够指定库应该公开所有这些控制器的根路径.插图:
// 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;
}
...
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.
所以在你的情况下,你的控制器就像:
@RestController
@RequestMapping("/${super.admin.path:admin}")
class AdminController {
// Same as before
}
前面的控制器将使用super.admin.path本地/系统属性或环境变量值作为其前缀或admin(如果未提供).如果您正在使用Spring Boot,请将以下内容添加到您的application.properties:
super.admin.path=whatever
您可以自定义该前缀.