Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot - how to get running port and ip address [duplicate]

I am passing the port via shell script while starting the spring boot application. Would like to know how to get the running port and system ip address in the application to print in log file.

script: -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9890

like image 849
Jessie Avatar asked Dec 24 '22 05:12

Jessie


2 Answers

You can autowire port number in any component class in following way

// Inject which port we were assigned
@Value("${local.server.port}")
int port;

Or with the annotation @LocalServerPort

@LocalServerPort
private int port;

And host address with following

String ip = InetAddress.getLocalHost().getHostAddress()
like image 126
Emdadul Sawon Avatar answered Feb 15 '23 10:02

Emdadul Sawon


If you want to get it after application running try with this:

@Component
public class ApplicationLoader implements ApplicationRunner {

    @Autowired
    private Environment environment;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(environment.getProperty("java.rmi.server.hostname"));
        System.out.println(environment.getProperty("local.server.port"));
        System.out.println(InetAddress.getLocalHost().getHostAddress());
    }
}

You can get port many ways:

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

or

@LocalServerPort
private int serverPort;
like image 42
GolamMazid Sajib Avatar answered Feb 15 '23 11:02

GolamMazid Sajib