Spring动态注册路由:如何解决控制器路由参数类型写死的问题?
spring动态注册控制器路由
问题中展示的代码可以实现路由注册,但由于参数类型写死了userdto.class,无法动态化。
要实现这一点,可以使用java反射机制获取方法的参数类型。以下是一个示例:
package dry.example.service.impl;import dry.example.route.CustomInvocationHandler;import dry.example.route.RouteAdmin;import dry.example.service.RouteService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.mvc.method.RequestMappingInfo;import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;import java.lang.reflect.Method;import java.lang.reflect.Proxy;@Servicepublic class RouteServiceImpl implements RouteService { @Autowired private RequestMappingHandlerMapping requestMappingHandlerMapping; @Override public void run(Object handler) { try {RequestMappingInfo requestMappingInfo = RequestMappingInfo.paths("testing").methods(RequestMethod.GET).build();Method method = handler.getClass().getMethod("h01", getParameterType(handler, "h01"));requestMappingHandlerMapping.registerMapping(requestMappingInfo, handler, method); } catch (Exception e) {e.printStackTrace(); } } private Class<?> getParameterType(Object handler, String methodName) throws NoSuchMethodException { Method method = handler.getClass().getMethod(methodName); return method.getParameterTypes()[0]; }}
在示例中,getparametertype 方法通过反射获取指定方法的第一个参数类型,从而实现参数类型的动态化。
以上就是Spring动态注册路由:如何解决控制器路由参数类型写死的问题?的详细内容,更多请关注范的资源库其它相关文章!