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
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()
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With