当然你可以对下面的 public static boolean available(int port) 进行改进,检查端口的可用性,因为有些端口虽然可用,但有时会被拒绝,如端口1024,依赖于操作系统,也可以从某些属性文件读取范围但不能使用Spring读取,因为范围是在上下文之前设置的加载,但这不应该是一个问题,我把所有东西放在一个文件中,以显示方法,使其看起来不漂亮
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class DemoApplication {
private static final int MIN_PORT = 1100; // to by set according to your
private static final int MAX_PORT = 9000; // needs or uploaded from
public static int myPort; // properties whatever suits you
public static void main(String[] args) {
int availablePort = MIN_PORT;
for (availablePort=MIN_PORT; availablePort < MAX_PORT; availablePort++) {
if (available(availablePort)) {
break;
}
}
if (availablePort == MIN_PORT && !available(availablePort)) {
throw new IllegalArgumentException("Cant start container for port: " + myPort);
}
DemoApplication.myPort = availablePort;
SpringApplication.run(DemoApplication.class, args);
}
public static boolean available(int port) {
System.out.println("TRY PORT " + port);
// if you have some range for denied ports you can also check it
// here just add proper checking and return
// false if port checked within that range
ServerSocket ss = null;
DatagramSocket ds = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
ds = new DatagramSocket(port);
ds.setReuseAddress(true);
return true;
} catch (IOException e) {
} finally {
if (ds != null) {
ds.close();
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
/* should not be thrown */
}
}
}
return false;
}
}
这是最重要的部分:
@Component
class CustomizationBean implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(DemoApplication.myPort);
}
}