这篇“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 {
}
添加一个配置类继承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前缀”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。