下面是详解SpringBoot修改启动端口server.port的四种方式的完整攻略:
下面是详解SpringBoot修改启动端口server.port的四种方式的完整攻略:
方式一:通过application.properties文件修改
在SpringBoot应用的classpath路径下添加application.properties文件,然后在文件中添加以下内容:
server.port=8081
这样就可以将应用的启动端口修改为8081了。
示例说明:
项目名称为sample,结构如下:
sample
├── src
│ ├── main
│ │ ├── java
│ │ │ └──com.sample
│ │ │ └──SampleApplication.java
│ │ └── resources
│ │ └── application.properties
application.properties文件中添加如下内容:
server.port=8081
方式二:通过命令行参数修改
在启动应用时增加--server.port=8081
参数,即可将应用的启动端口修改为8081。
示例说明:
假设我们的jar包名称为sample.jar,执行的命令为:
java -jar sample.jar --server.port=8081
方式三:通过系统环境变量修改
在系统环境变量中添加SERVER_PORT=8081
,重启应用即可将应用的启动端口修改为8081。
示例说明:
在Windows系统中,我们可以在命令行输入以下命令:
set SERVER_PORT=8081
在Linux系统中,我们可以在命令行输入以下命令:
export SERVER_PORT=8081
方式四:通过自定义配置类修改
创建一个配置类,使用@ConfigurationProperties(prefix = "server")
注解将配置文件中server.
开头的属性注入到该类中,然后将server.port属性修改为8081即可。
示例说明:
创建一个名为ServerConfig
的配置类:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "server")
public class ServerConfig {
private int port;
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
在application.properties文件中添加以下内容:
server.port=8080
然后在需要修改端口的地方注入ServerConfig即可:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleApplication {
@Autowired
private ServerConfig serverConfig;
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
在需要修改端口时,修改ServerConfig的port属性即可:
serverConfig.setPort(8081);
本文标题为:详解SpringBoot修改启动端口server.port的四种方式
- SpringSecurity添加图形验证码认证实现 2023-04-12
- Java数据结构之链表的增删查改详解 2023-05-08
- SpringBoot项目部署到阿里云服务器的实现步骤 2023-02-05
- Ajax request response 乱码解决方法 2024-01-30
- Java Map接口概述和常用方法详解 2023-06-30
- 如何在我的java代码中检索mysql数据库中的sha1哈希值 2023-11-02
- IDEA报错:无效的源发行版解决方案 2023-05-08
- Java C++ leetcode执行一次字符串交换能否使两个字符串相等 2023-06-10
- SpringBoot整合RabbitMQ实现六种工作模式的示例 2023-03-21
- 动态创建script标签实现跨域资源访问的方法介绍 2024-01-27