0


SpringBoot全局设置请求路径增加前缀

方式1:配置文件

直接通过配置文件设置

#spring boot 默认上下文为/,可以通过server.context-path进行修改
server.context-path=/spring-boot

https://www.cnblogs.com/a-du/p/13293222.html

方式2: 修改WebMvcConfigurer

@Component
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 匹配所有的路径
                .allowCredentials(true) // 设置允许凭证
                .allowedHeaders("*")   // 设置请求头
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 设置允许的方式
                .allowedOriginPatterns("*");
    }

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer
                .addPathPrefix("/myapi",c -> c.isAnnotationPresent(RestController.class));
    }
}

方式3: 自定义注解ApiRestController

1.增加自定义注解ApiRestController

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public @interface ApiRestController {
    @AliasFor(annotation = RequestMapping.class)
    String name() default "";

    @AliasFor(annotation = RequestMapping.class)
    String[] value() default {};

    @AliasFor(annotation = RequestMapping.class)
    String[] path() default {};

}
  1. 替换@RestController到注解@ApiRestController
@ApiRestController("students")
public class StudentController {
}
  1. 配置WebMvcConfigurer
@Component
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer
                .addPathPrefix("/myapi",c -> c.isAnnotationPresent(ApiRestController.class));
    }
}
标签: spring boot 后端 java

本文转载自: https://blog.csdn.net/myli92/article/details/139014360
版权归原作者 tomorrow.hello 所有, 如有侵权,请联系我们删除。

“SpringBoot全局设置请求路径增加前缀”的评论:

还没有评论