Spring boot 随机端口

#配置网站启动的随机端口
server.port=0
#或者指定范围
server.port=${random.int[8900,9900]}

 

 

1.在程序主口目录下增加以下类

`

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 功能描述:
 * 获取服务的端口号
 *
 * 
 *  * 
 **/

@Component
public class SpringBootWebServiceInfoUtil implements ApplicationListener {
    public int getServerPort() {
        return serverPort;
    }
    private int serverPort;

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

`

2.使用时:

 @Component
public class HttpClientUtil {
    private String member;
    @Autowired
    private pringBootWebServiceInfoUtil serverConfig;
    
    private String getImgUrl(String fileName) {
        return serverConfig.getUrl()+getRelativeDir()+ fileName;
    }
 }


 

你可能感兴趣的:(java)