
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];
}
}修改部分:
这样,参数类型就可以动态获取,无需写死在代码中。
以上就是Spring动态路由注册:如何避免硬编码控制器参数类型?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号