Spring Boot如何改变端口号和上下文路径

x33g5p2x  于2022-10-06 转载在 Spring  
字(2.1k)|赞(0)|评价(0)|浏览(407)

在这篇文章中,我们将讨论几种改变Spring Boot应用程序中默认端口和上下文路径的方法。 
的默认端口和上下文路径。

我们首先讨论如何改变嵌入式服务器的默认端口,因为我们知道在默认情况下,嵌入式服务器是从8080端口启动的。

改变嵌入式服务器的默认端口

一个常见的用例是改变嵌入式服务器的默认端口。

使用application.properties文件

定制Spring Boot的最快和最简单的方法是覆盖默认属性的值。

对于服务器端口,我们要改变的属性是server.port
默认情况下,嵌入式服务器在8080端口启动。让我们看看我们如何在application.properties文件中提供一个不同的值。

现在服务器将在端口http://localhost:8081上启动。

同样,如果我们使用application.yml文件,我们也可以这样做。

server:
  port: 8081

如果把这两个文件放在Maven应用的src/main/resources目录下,Spring Boot会自动加载。

程序性配置

我们可以通过在启动应用程序时设置特定属性或定制嵌入式服务器配置,以编程方式配置端口。

首先,我们来看看如何在主@SpringBootApplication类中设置该属性。

import java.util.Collections;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Springboot2WebappJspApplication {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Springboot2WebappJspApplication.class);
        app.setDefaultProperties(Collections.singletonMap("server.port", "8081"));
        app.run(args);
        
    }
}

使用命令行参数

当把我们的应用程序打包并作为jar运行时,我们可以用java命令设置server.port的一个参数:

java -jar springboot2webapp.jar --server.port=8083

或者通过使用等效的语法。

java -jar -Dserver.port=8083 springboot2webapp.jar

如何改变默认的上下文路径?

有几种方法可以改变默认的上下文路径。

使用application.properties文件

/src/main/resources/application.properties

server.port=8080
server.servlet.context-path=/springboot2webapp

默认情况下,上下文路径是"/"。要改变上下文路径,请覆盖并更新server.servlet.context-path属性。下面的例子将上下文路径从/更新为/springboot2webapp或http://localhost:8080/springboot2webapp 就像许多其他配置选项一样,Spring Boot中的上下文路径可以通过设置一个属性来改变,即server.servlet.context-path
注意,这对Spring Boot 2.x有效。

对于Boot 1.x,该属性为server.context-path

以程序方式改变上下文路径

SpringApplication有一个方法是setDefaultProperties(),用于改变spring boot的默认属性。

import java.util.Collections;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Springboot2WebappJspApplication {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Springboot2WebappJspApplication.class);
        app.setDefaultProperties(Collections.singletonMap("server.servlet.context-path", "/springboot2webapp"));
        app.run(args);
    }
}

相关文章