SpringBoot多controller如何添加URL前缀

WBOY
풀어 주다: 2023-05-12 18:37:20
앞으로
1828명이 탐색했습니다.
前言

在某些情况下,服务的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多controller如何添加URL前缀의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:yisu.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!