在使用Spring Boot进行开发时,有时候我们需要在启动应用时指定端口,而不是每次都使用默认端口。这篇文章将详细介绍如何在Spring Boot应用启动时指定端口。

整体流程如下:

| 步骤 | 操作 |
|------------|--------------------------------------------|
| 1 | 在application.properties中配置默认端口 |
| 2 | 创建一个自定义配置类 |
| 3 | 在自定义配置类中设置端口配置属性 |
| 4 | 在启动类中引用自定义配置类 |
| 5 | 启动应用程序 |

下面将逐步介绍每一步需要做的内容及相应的代码示例:

### 步骤一:在application.properties中配置默认端口

在Spring Boot项目中,一般会有一个application.properties文件,我们可以在其中配置默认端口,如下所示:

```properties
server.port=8080
```

这样就可以指定应用程序的默认端口为8080。

### 步骤二:创建一个自定义配置类

在项目中创建一个新的配置类,用来接收外部传入的端口参数。

```java
package com.example.demo.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties("custom")
public class CustomProperties {
private int port;

public int getPort() {
return port;
}

public void setPort(int port) {
this.port = port;
}
}
```

### 步骤三:在自定义配置类中设置端口配置属性

在自定义配置类中添加一个属性来接收指定的端口参数。

### 步骤四:在启动类中引用自定义配置类

在Spring Boot应用的启动类中引入自定义配置类,并通过@Value注解来获取指定的端口参数。

```java
package com.example.demo;

import com.example.demo.config.CustomProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

@Autowired
private CustomProperties customProperties;

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

@Override
public void run(String... args) {
System.out.println("Using port: " + customProperties.getPort());
}

// 配置Tomcat的端口
@Bean
public TomcatServletWebServerFactory tomcatFactory() {
return new TomcatServletWebServerFactory() {
@Override
protected void customizeConnector(Connector connector) {
int port = customProperties.getPort();
connector.setPort(port);
}
};
}
}
```

### 步骤五:启动应用程序

现在,可以通过指定的端口启动Spring Boot应用程序了。在启动应用程序时,可以通过命令行参数的形式传入自定义的端口,如`--custom.port=9090`。

总结一下,通过以上步骤,我们可以在Spring Boot应用启动时指定端口。这样可以灵活地根据实际需求来配置端口,而不是固定使用默认端口。希望这篇文章对初学者能够有所帮助,帮助他们更好地理解和使用Spring Boot。