如何在 Spring Boot 中为所有控制器指定前缀? [英] How to specify prefix for all controllers in Spring Boot?

查看:33
本文介绍了如何在 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

这篇关于如何在 Spring Boot 中为所有控制器指定前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆