获取Spring Boot的应用程序端点绝对完整路径

问题描述 投票:0回答:1

有时需要快速测试 Spring Boot 应用程序(不是我生成的),但由于复杂的属性和一些意大利面条式代码会更改某处的路径,因此无法轻松调用端点。

是否有任何方法可以在开始时公开

full absolute
端点路径? 像这样:https://stackoverflow.com/a/43543204/10894456但我需要带有端口的完整绝对路径

spring-boot spring-mvc servlets
1个回答
0
投票

在 Spring Boot 应用程序中,您可以通过检查应用程序的

ServletContext
来获取公开端点的完整绝对路径以及端口。您可以创建一个公开此信息的自定义 Spring Bean。以下是如何实现此目标的示例:

  1. 创建自定义 bean 来公开端点信息:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Map;

@Component
public class EndpointInfoProvider {
    private final ServletContext servletContext;

    @Autowired
    public EndpointInfoProvider(ServletWebServerApplicationContext applicationContext) {
        this.servletContext = applicationContext.getServletContext();
    }

    public Map<String, String> getEndpointInfo() {
        Map<String, String> endpointInfo = new HashMap<>();
        
        // Get the server port
        int serverPort = servletContext.getRealServerPort();
        
        // Get the context path (e.g., /your-app-context)
        String contextPath = servletContext.getContextPath();
        
        // Iterate through all the registered servlets and their mappings
        servletContext.getServletRegistrations().forEach((name, registration) -> {
            registration.getMappings().forEach(mapping -> {
                String servletPath = mapping.replaceAll("\\*", "");
                String fullPath = "http://localhost:" + serverPort + contextPath + servletPath;
                endpointInfo.put(name, fullPath);
            });
        });
        
        return endpointInfo;
    }
}
  1. 现在您可以将此 bean 注入控制器或服务中以访问端点信息:
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.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api")
public class MyController {
    private final EndpointInfoProvider endpointInfoProvider;

    @Autowired
    public MyController(EndpointInfoProvider endpointInfoProvider) {
        this.endpointInfoProvider = endpointInfoProvider;
    }

    @GetMapping("/endpoints")
    public Map<String, String> getEndpoints() {
        return endpointInfoProvider.getEndpointInfo();
    }
}

在此示例中,

/api/endpoints
端点将返回 servlet 名称(通常是 bean 名称)及其相应的完整绝对 URL(包括端口)的映射。

如果您决定公开此信息,请确保您有适当的错误处理和安全措施,因为如果在生产环境中没有得到适当的保护,它可能会带来安全风险。

© www.soinside.com 2019 - 2024. All rights reserved.