SpringBoot2为接口统一加url前缀的实现示例
更新时间:2026年03月08日 09:19:56 作者:小恒恒
本文主要介绍了SpringBoot2为接口统一加url前缀的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
背景
有时候会面临前后端都放在一起的情况,这个时候我们就不好去使用配置中的 server.servlet.context-path ,经过一番查找,发现使用注解还是挺方便的。
解决办法
定义注解
package com.example.demo.annotation;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import java.lang.annotation.*;
/**
* controller层统一使用该注解
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RestController
public @interface ApiRestController {
/**
* Alias for {@link Controller#value}.
*/
@AliasFor(annotation = Controller.class)
String value() default "";
}
实现WebMvcConfigurer配置路径前缀
package com.example.demo.config;
import com.example.demo.annotation.ApiRestController;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 配置统一的后台接口访问路径的前缀
*/
@Configuration
public class CustomWebMvcConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer
.addPathPrefix("/api", c -> c.isAnnotationPresent(ApiRestController.class));
}
}
在Controller类上使用注解
package com.example.demo.controller.api;
import com.example.demo.annotation.ApiRestController;
import org.springframework.web.bind.annotation.GetMapping;
@ApiRestController
@RequestMapping("/token")
public class UserTokenController {
/**
* 获取 user token
*/
@GetMapping("/getUserToken")
public ResponseBase getUserToken(HttpServletRequest request, HttpServletResponse response){
}
}
到此这篇关于SpringBoot2为接口统一加url前缀的实现示例的文章就介绍到这了,更多相关SpringBoot2 接口统一加url前缀内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
详解Spring Security的Web应用和指纹登录实践
这篇文章主要介绍了详解Spring Security的Web应用和指纹登录实践,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2019-03-03
Spring Boot集成kubernetes客户端实现API操作k8s集群的方案
Kubernetes是一个开源的容器编排平台,可以自动化在部署、管理和扩展容器化应用过程中涉及的许多手动操作,这篇文章主要介绍了Spring Boot集成kubernetes客户端实现API操作k8s集群,需要的朋友可以参考下2024-08-08
SpringMVC使用@PathVariable接收参数过程解析
这篇文章主要介绍了SpringMVC使用@PathVariable接收参数过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2020-10-10
SpringBoot在自定义类中调用service层mapper层方式
这篇文章主要介绍了SpringBoot在自定义类中调用service层mapper层方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2025-03-03


最新评论