How to get the SPRING Boot HOST and PORT address during run time?

北战南征 提交于 2019-12-04 16:17:35

问题


How could I get the host and port where my application is deployed during run-time so that I can use it in my java method?


回答1:


You can get this information via Environment for the port and the host you can obtain by using 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();
}



回答2:


If you use random port like server.port=${random.int[10000,20000]} method. and in Java code read the port in Environment use @Value or getProperty("server.port"). You will get a Unpredictable Port Because it is Random.

ApplicationListener, you can override onApplicationEvent to get the port number once it's set.

In Spring boot version Implements Spring interface ApplicationListener<EmbeddedServletContainerInitializedEvent>(Spring boot version 1) or ApplicationListener<WebServerInitializedEvent>(Spring boot version 2) override onApplicationEvent to get the Fact Port .

Spring boot 1

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

Spring boot 2

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



回答3:


For the Host: As mentionned by Anton

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

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

Port: As mentioned by Nicolai, you can retrieve this information by the environment property only if it is configured explicitly and not set to 0.

Spring documentation on the subject: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html#howto-discover-the-http-port-at-runtime

For the actual way to do this, it was answered here: Spring Boot - How to get the running port

And here's a github example on how to implement it: https://github.com/hosuaby/example-restful-project/blob/master/src/main/java/io/hosuaby/restful/PortHolder.java




回答4:


Just a complete example for answers above

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();
        }
    }
}



回答5:


The port has been bind in runtime could been injected as:

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



回答6:


Here is an util component:

EnvUtil.java
(Put it in proper package, to become a component.)

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();
    }
}

Example - use the util:

Then could inject the util, and call its method.
Here is an example in a controller:

// 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;
}


来源:https://stackoverflow.com/questions/38916213/how-to-get-the-spring-boot-host-and-port-address-during-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!