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

2022-08-31 10:55:06

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

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

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

我想分别通过 URL 和 访问这些内容。http://localhost:8080/api/usershttp://localhost:8080/api/orders

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


答案 1

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

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;
    }
}

或将其添加到您的 in 文件夹中application.propertiessrc\main\resources

server.contextPath=/api

编辑

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

server.servlet.contextPath=/api

更多你在这里找到 Spring Boot Context Root 和这里 将 servlet 映射添加到 DispatcherServlet


答案 2

如果你想为一些控制器添加前缀,我发现了另外两个解决方案

选项 1 - 使用弹簧 SpEL 为控制器添加前缀变量

@RestController
@RequestMapping(path = "${v1API}/users")
public class V1FruitsController {

    @GetMapping(path = "")
    @ResponseBody
    public String list(){
        return "[\"Joe\", \"Peter\"]";
    }
}

应用程序.属性

v1API=/api/v1

选项 2 - 创建自定义控制器注释

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
@RequestMapping("/api/v1")
public @interface V1APIController {
    @AliasFor(annotation = Component.class)
    String value() default "";
}


@V1APIController
public class UserController {

    @RequestMapping("/users")
    @ReponseBody
    public String index(){
        return "[\"Joe\", \"Peter\"]";
    }
}

然后测试它

curl -X GET localhost:8080/api/v1/users

推荐