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

Mur*_*ali 50 java spring spring-boot

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

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

@RestController
@RequestMapping("/orders")
public class OrderController {
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

Tom*_*nek 54

您可以/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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

server.contextPath=/api/*
Run Code Online (Sandbox Code Playgroud)

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

  • 这会为所有内容添加前缀,而不仅仅是控制器 (48认同)
  • 它应该只是"server.contextPath =/api /".有一个尾随*导致Spring Boot 1.3.5版本出错 (13认同)
  • 对于 Spring Boot 2.0,它必须类似于 `server.servlet.context-path=/api`。 (7认同)
  • 位于`application.properties`文件中的`server.servlet.context-path =/api/*`给了我`注册Tomcat的错误:type = TomcatEmbeddedWebappClassLoader,host = localhost,context =/api/* - ContextPath必须以'/'开头而不以'/'错误结束.不带引号的`server.servlet.context-path =/api`属性是应用程序启动所需的属性. (5认同)

deF*_*tas 21

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

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

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

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

application.properties

v1API=/api/v1
Run Code Online (Sandbox Code Playgroud)

选项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\"]";
    }
}
Run Code Online (Sandbox Code Playgroud)

然后测试一下

curl -X GET localhost:8080/api/v1/users
Run Code Online (Sandbox Code Playgroud)

  • 是的,但是如果您的UserController中有很多方法该怎么办?现在,您已经在类级别权衡了编写@RequestMapping(“ / api / users”)的过程,以在每个方法的RequestMapping前面加上“ users”作为前缀。 (4认同)

Bis*_*wal 11

application.propertiesas 中添加您的默认路径:

server.servlet.contextPath=/mainPath
Run Code Online (Sandbox Code Playgroud)

这里/mainPath将是所有控制器的前缀


Edu*_*rdo 9

如果您使用的是Spring Boot 2(Spring框架5),那么您的中的属性将被替换application.properties

server.contextPath
Run Code Online (Sandbox Code Playgroud)

对于:

server.servlet.context-path=
Run Code Online (Sandbox Code Playgroud)


dow*_*eyt 8

除了有关更改上下文路径的应用程序属性的其他注释之外,您还可以使用应用程序属性单独设置调度程序 servlet 的前缀,在 Spring Boot 2.3.1 中。

spring.mvc.servlet.path=/api
Run Code Online (Sandbox Code Playgroud)

控制器中的请求映射不会改变。虽然上下文路径将整个应用程序移动到不同的路径,但 servlet 路径仅限制由调度程序 servlet 处理的 URL。servlet 路径相当于 web.xml 中的 servlet 映射。可以从任何其他 URL 访问不使用调度程序 servlet 的其他资源。

如果您有其他未映射到/api前缀的控制器,那么这将不起作用,除非您为这些控制器声明具有不同前缀的第二个调度程序 servlet。


小智 7

spring-webmvc-5.1.x 起

import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerTypePredicate;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix("/api",
                HandlerTypePredicate.forAnnotation(RestController.class));
    }
}
Run Code Online (Sandbox Code Playgroud)