spring webflux 动态注册controller
spring webflux 动态注册controller的方法比较多,以下简单说明下
函数式模式
- 参考玩法
官方比较推荐的
@Bean
public RouterFunction<ServerResponse> dynamicRoutes(ApplicationContext ctx) {
RouterFunctions.Builder builder = RouterFunctions.route();
// 从配置/数据库读取路由定义
for (RouteDef def : fetchRouteDefinitions()) {
builder = builder.route(
RequestPredicates.path(def.getPath()).and(RequestPredicates.method(def.getMethod())),
request -> ServerResponse.ok().bodyValue(def.getHandler().handle(request))
);
}
return builder.build();
}
RequestMappingHandlerMapping 模式
尽管与webmvc 有一些差异,但是内部机制还是一样的,RequestMappingHandlerMapping 依然还是可以使用的
@Configuration
public class DynamicControllerConfig {
@Autowired
private RequestMappingHandlerMapping handlerMapping;
@Autowired
private MyHandler myHandler;
@PostConstruct
public void register() throws NoSuchMethodException {
RequestMappingInfo info = RequestMappingInfo
.paths("/dynamic")
.methods(RequestMethod.GET)
.build();
Method method = MyHandler.class.getMethod("handle", ServerRequest.class);
handlerMapping.registerMapping(info, myHandler, method);
}
}
参考资料
https://docs.spring.io/spring-framework/reference/web/webflux/controller/ann-requestmapping.html
浙公网安备 33010602011771号