spring 动态注册控制器路由
问题:
如何动态注册 spring 控制器路由,而不必写死参数类型?
答案:
为了动态化参数类型,可以使用 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; @Service public 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 方法通过反射获取指定方法的第一个参数类型。
- h01 方法的参数类型从 userdto.class 更改为动态获取的参数类型。
这样,参数类型就可以动态获取,无需写死在代码中。
以上就是Spring动态路由注册:如何避免硬编码控制器参数类型?的详细内容,更多请关注图灵教育其它相关文章!