如何在运行时获取SPRING Boot HOST和PORT地址?

时间:2016-08-12 10:51:58

标签: spring-boot port host

如何在运行时获取部署应用程序的主机和端口,以便我可以在我的java方法中使用它?

6 个答案:

答案 0 :(得分:15)

您可以通过Environment获取port以及使用host可获得的InternetAddress来获取此信息。

@Autowired
Environment environment;

......
public void somePlaceInTheCode() {
    // Port
    environment.getProperty("server.port");
    // Local address
    InetAddress.getLocalHost().getHostAddress();
    InetAddress.getLocalHost().getHostName();

    // Remote address
    InetAddress.getLoopbackAddress().getHostAddress();
    InetAddress.getLoopbackAddress().getHostName();
}

答案 1 :(得分:1)

如果您使用server.port=${random.int[10000,20000]}之类的随机端口。然后在Java代码中使用Environment@Value读取getProperty("server.port")中的端口。 您将获得一个不可预测的端口,因为它是随机的。

ApplicationListener,您可以重写onApplicationEvent以获取设置后的端口号。

在Spring引导版本中,实现Spring接口ApplicationListener<EmbeddedServletContainerInitializedEvent>(Spring引导版本1)或ApplicationListener<WebServerInitializedEvent>(Spring引导版本2)覆盖onApplicationEvent以获得事实端口。

春季靴1

@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
    int port = event.getEmbeddedServletContainer().getPort();
}

春季靴2

@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
    Integer port = event.getWebServer().getPort();
    this.port = port;
}

答案 2 :(得分:0)

只是上述答案的完整示例

package bj;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;

import java.net.InetAddress;
import java.net.UnknownHostException;

@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@SpringBootApplication
class App implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private ApplicationContext applicationContext;

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        try {
            String ip = InetAddress.getLocalHost().getHostAddress();
            int port = applicationContext.getBean(Environment.class).getProperty("server.port", Integer.class, 8080);
            System.out.printf("%s:%d", ip, port);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

答案 3 :(得分:0)

在运行时已绑定端口的端口可以注入为:

@Value('${local.server.port}')
private int port;

答案 4 :(得分:0)

这是一个util组件:

EnvUtil.java
(将其放入适当的包装中,成为组件。)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Environment util.
 */
@Component
public class EnvUtil {
    @Autowired
    Environment environment;

    private String port;
    private String hostname;

    /**
     * Get port.
     *
     * @return
     */
    public String getPort() {
        if (port == null) port = environment.getProperty("local.server.port");
        return port;
    }

    /**
     * Get port, as Integer.
     *
     * @return
     */
    public Integer getPortAsInt() {
        return Integer.valueOf(getPort());
    }

    /**
     * Get hostname.
     *
     * @return
     */
    public String getHostname() throws UnknownHostException {
        // TODO ... would this cache cause issue, when network env change ???
        if (hostname == null) hostname = InetAddress.getLocalHost().getHostAddress();
        return hostname;
    }

    public String getServerUrlPrefi() throws UnknownHostException {
        return "http://" + getHostname() + ":" + getPort();
    }
}

示例-使用实用程序:

然后可以注入util,并调用其方法。
这是控制器中的示例:

// inject it,
@Autowired
private EnvUtil envUtil;

/**
 * env
 *
 * @return
 */
@GetMapping(path = "/env")
@ResponseBody
public Object env() throws UnknownHostException {
    Map<String, Object> map = new HashMap<>();
    map.put("port", envUtil.getPort());
    map.put("host", envUtil.getHostname());
    return map;
}

答案 5 :(得分:-1)

主持人: 正如Anton所提到的那样

// Local address
InetAddress.getLocalHost().getHostAddress();
InetAddress.getLocalHost().getHostName();

// Remote address
InetAddress.getLoopbackAddress().getHostAddress();
InetAddress.getLoopbackAddress().getHostName();

端口: 正如Nicolai所提到的,只有在显式配置且未设置为0的情况下,才能通过environment属性检索此信息。

关于这个主题的Spring文档: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html#howto-discover-the-http-port-at-runtime

对于实际的方法,这里得到了回答: Spring Boot - How to get the running port

以下是关于如何实现它的github示例: https://github.com/hosuaby/example-restful-project/blob/master/src/main/java/io/hosuaby/restful/PortHolder.java