如何在Spring Boot中为所有控制器指定前缀? [英] How to specify prefix for all controllers in Spring Boot?
本文介绍了如何在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
。
I want to access these by URL at http://localhost:8080/api/users
and http://localhost:8080/api/orders
, respectively.
我如何实现这一目标春季靴子?
How do I achieve this in 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;
}
}
或将此项添加到您的 application.properties
in src\main\resources
folder
or add this to your application.properties
in src\main\resources
folder
server.contextPath=/api/*
你在这里找到更多 Spring Boot Context Root 和将servlet映射添加到DispatcherServlet
这篇关于如何在Spring Boot中为所有控制器指定前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文