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

我有控制器映射/user/order

@RestController

@RequestMapping("/users")

public class UserController {

...

}

@RestController

@RequestMapping("/orders")

public class OrderController {

...

}

我想分别通过URL http://localhost:8080/api/users 和来访问它们http://localhost:8080/api/orders。

如何在Spring Boot" title="Spring Boot">Spring Boot中实现这一目标?

回答:

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

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;

}

}

或将此添加到你的application.properties in src\main\resources文件夹中

server.contextPath=/api/*

编辑

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

server.servlet.contextPath=/api/*

以上是 如何在Spring Boot中为所有控制器指定前缀? 的全部内容, 来源链接: utcz.com/qa/411981.html

回到顶部