Spring boot - 如何获取运行端口和IP地址

Jes*_*sie 4 java spring spring-boot

我在启动 spring 启动应用程序时通过 shell 脚本传递端口。想知道如何在应用程序中获取运行端口和系统IP地址以打印在日志文件中。

脚本:-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9890

Emd*_*won 5

您可以通过以下方式在任何组件类中自动装配端口号

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

或者用注释 @LocalServerPort

@LocalServerPort
private int port;
Run Code Online (Sandbox Code Playgroud)

和主机地址如下

String ip = InetAddress.getLocalHost().getHostAddress()
Run Code Online (Sandbox Code Playgroud)


saj*_*jib 4

如果您想在应用程序运行后获取它,请尝试以下操作:

@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());
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以通过多种方式获取端口:

@Value("${local.server.port}")
private int serverPort;
Run Code Online (Sandbox Code Playgroud)

或者

@LocalServerPort
private int serverPort;
Run Code Online (Sandbox Code Playgroud)