在Spring boot中指定随机可用的端口
warning:
这篇文章距离上次修改已过432天,其中的内容可能已经有所变动。
在Spring Boot中,你可以通过设置server.port属性为0来指定应用程序使用一个随机可用的端口。Spring Boot会自动选择一个未被使用的端口号。
这里是如何在application.properties或application.yml文件中设置的例子:
application.properties 文件:
server.port=0application.yml 文件:
server:
port: 0然后,在你的Spring Boot应用程序中,你可以通过注入Environment来获取实际分配给应用程序的端口号:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class PortInfo {
@Autowired
private Environment env;
public int getPort() {
return env.getProperty("local.server.port", Integer.class);
}
}当你的应用程序启动时,Spring Boot会在控制台上打印出所选择的随机端口号,例如:
The following profiles are active: dev
Server started on port(s): 0 (http) with context path ''在这个例子中,Server started on port(s): 0 (http) with context path '' 表示应用程序被分配了0端口号,实际使用的端口会在日志中显示。
评论已关闭