如何在 spring 启动应用程序中获取特定的应用程序路由域、端口和路径?

How to get an specific application route in spring boot application with domain, port and path?

我在 Whosebug 中发现了类似的问题,但没有可接受的答案。

get application domain + port and path programmatically in spring?

我想发送电子邮件验证 link。 例如:https://host:port/path?encrypted_email=encrypted-data-of-user-email

我想将此 URL 从注册控制器发送到用户的电子邮件。但我不会写硬编码的Http/https、主机、端口和验证电子邮件的路径。我想使用 spring 启动的帮助来获得它。我该怎么办以及如何克服这种情况?

谢谢

在包括 Whosebug 在内的所有地方进行搜索之后。我发现了这个:

获取主机:

String host = InetAddress.getLocalHost().getHostName();

获取端口:

// In your application.properties
server.port=8080
String port = environment.getProperty("server.port");

上面我也写了例子class

import org.springframework.core.env.Environment;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class ApiUrl {

    private final Environment environment;
    public static final String apiUrlPrefix = "/api";
    public static final String apiVersion = "/v1";

    public ApiUrl(Environment environment) {
        this.environment = environment;
    }

    public String getApiBaseUrl() throws UnknownHostException {
        String host = InetAddress.getLocalHost().getHostName();
        String port = environment.getProperty("server.port");

        return "https://" + host +":"+ port + apiUrlPrefix + apiVersion;
    }
}

我希望这对人们有所帮助。

更多学习参考资料:

https://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/Environment.html