SpringBoot多controller添加URL前缀的实现方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot多controller添加URL前缀的实现方法

码农-文若书生   2023-03-21 我要评论

前言

在某些情况下,服务的controller中前缀是一致的,例如所有URL的前缀都为/context-path/api/v1,需要为某些URL添加统一的前缀。

能想到的处理办法为修改服务的context-path,在context-path中添加api/v1,这样修改全局的前缀能够解决上面的问题,但存在弊端,如果URL存在多个前缀,例如有些URL需要前缀为api/v2,就无法区分了,如果服务中的一些静态资源不想添加api/v1,也无法区分。

下面通过自定义注解的方式实现某些URL前缀的统一添加。

一、配置文件内添加前缀配置

如果需要多种前缀,添加多组配置,例如添加:api.prefix.v2=/api/v2

###############url前缀配置##################
api.prefix.v1=/api/v1

二、配置映射的实体

@Data
@Component
@ConfigurationProperties(prefix = "api.prefix")
public class ApiPrefix {
    private String v1;
}

三、自定义注解

此注解功能与@RestController一致,对应api.prefix.v1的配置,如果有多组配置,定义多个注解即可

@RestController
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiV1RestController {
}

四、自定义PathMatch添加前缀

添加一个配置类继承WebMvcConfigurer,重写configurePathMatch方法,为类上有ApiV1RestController注解的controller中的接口添加对应的前缀。

@AutoConfiguration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    private ApiPrefix apiPrefix;
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix(apiPrefix.getV1(), c -> c.isAnnotationPresent(ApiV1RestController.class));
    }
}

五、测试

需要在对应的controller上使用@ApiV1RestController注解代替@RestController注解

@ApiV1RestController
@RequestMapping("/test/apiv1")
public class TestApiV1RestController {
    @GetMapping()
    public ResponseEntity get() {
        return new ResponseEntity();
    }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们