登录
首页 >  文章 >  java教程

Spring动态路由注册:如何避免硬编码控制器参数类型?

时间:2024-12-04 09:48:48 427浏览 收藏

怎么入门文章编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《Spring动态路由注册:如何避免硬编码控制器参数类型?》,涉及到,有需要的可以收藏一下

Spring动态路由注册:如何避免硬编码控制器参数类型?

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动态路由注册:如何避免硬编码控制器参数类型?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>