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

发布于:2024-05-18 ⋅ 阅读:(201) ⋅ 点赞:(0)

方式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 {};

}

2. 替换@RestController到注解@ApiRestController

@ApiRestController("students")
public class StudentController {
}

3. 配置WebMvcConfigurer

@Component
public class MyWebMvcConfigurer implements WebMvcConfigurer {

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


网站公告

今日签到

点亮在社区的每一天
去签到