SpringBoot多controller如何添加URL前缀

这篇“SpringBoot多controller如何添加URL前缀”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“SpringBoot多controller如何添加URL前缀”文章吧。

前言

在某些情况下,服务的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();
    }
}

SpringBoot多controller如何添加URL前缀  springboot 第1张

以上就是关于“SpringBoot多controller如何添加URL前缀”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注蜗牛博客行业资讯频道。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接