如何在 Spring Boot 中为所有控制器指定前缀?

如何在 Spring Boot 中为所有控制器指定前缀?

问题描述:

我有到 /user/order 的控制器映射:

I have controller mappings to /user and /order:

@RestController
@RequestMapping("/users")
public class UserController {
    ...
}

@RestController
@RequestMapping("/orders")
public class OrderController {
    ...
}

我想分别通过 http://localhost:8080/api/usershttp://localhost:8080/api/orders 的 URL 访问这些.

I want to access these by URL at http://localhost:8080/api/users and http://localhost:8080/api/orders, respectively.

我如何在 Spring Boot 中实现这一点?

How do I achieve this in Spring Boot?

您可以在自定义配置中提供一个映射到 Spring Boot 应用程序的根上下文路径到 /api/*.

You can provide a mapping to root context path of your spring boot application to /api/* in your custom configuration.

import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;

@Configuration
public class DispatcherServletCustomConfiguration {

    @Bean
    public DispatcherServlet dispatcherServlet() {
        return new DispatcherServlet();
    }

    @Bean
    public ServletRegistrationBean dispatcherServletRegistration() {
        ServletRegistrationBean registration = new ServletRegistrationBean(
                dispatcherServlet(), "/api/");
        registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
        return registration;
    }
}

或将其添加到 srcmain esources 文件夹中的 application.properties 文件夹

or add this to your application.properties in srcmain esources folder

server.contextPath=/api/*

编辑

从 Spring Boot 2.x 开始,该属性已被弃用,应替换为

server.servlet.contextPath=/api/*

您可以在此处Spring Boot Context Root 和此处添加servlet映射到DispatcherServlet