java 如何在运行时更改端点

57hvy0tb  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(106)

如何在运行时更改端点
示例:GET localhost:8080/old-endpoint
如何设置相同端点URL以获取localhost:8080/new-point
我发现了“${dynamic.endpoint}”并从www.example.com读取application.properties,但我不想要它。我正在尝试根据if else块编辑端点。
我知道路径变量或请求参数或控制从application.properties但它不为我工作

h43kikqp

h43kikqp1#

您有/old/switch端点。
调用/switch后,/old停止工作(因为unregisterMapping),而/new工作(因为registerMapping)。
新方法处理程序的逻辑作为Method从java反射传递。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

@RestController
@RequestMapping("/api/testing")
public class TestingController {
    @Autowired
    RequestMappingHandlerMapping mappingHandler;

    @GetMapping("/switch")
    public void switchHandler() throws Exception {
        RequestMappingInfo oldInfo = RequestMappingInfo.paths("/api/testing/old")
                .methods(RequestMethod.GET)
                .build();
        mappingHandler.unregisterMapping(oldInfo);

        RequestMappingInfo newInfo = RequestMappingInfo.paths("/api/testing/new")
                .methods(RequestMethod.GET)
                .build();
        Method method = this.getClass().getDeclaredMethod("oldHandler");
        mappingHandler.registerMapping(newInfo, this, method);
    }

    @GetMapping("/old")
    public void oldHandler() {
        System.out.println("old endpoint");
    }
}

相关问题