前言
在web开发中,自定义路径是非常重要的,它可以更容易的区分不同服务和不同的功能模块,使后端服务接口变得更加有序(完全无规则的接口简直糟糕透了) ,springboot经常用于web开发,当然也可以进行路径的自定义,这篇文章就是记录如何在springboot中进行自定义接口路径的开发.
环境准备
版本
| 依赖 | 版本 |
|---|---|
| jdk | 21 |
| springboot | 3.5.6 |
pom依赖
<parent>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-parent</artifactid>
<version>3.5.6</version>
</parent>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceencoding>utf-8</project.build.sourceencoding>
</properties>
<dependencies>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
</dependencies>只需要进行路径配置,只用到基础的springboot的web依赖和jdk.
代码步骤
1、全局路径
在springboot中如果想整个应用程序都使用自定义的路径前缀,可以直接在配置文件中进行配置,该配置主要用于标识运行某一个程序或服务. 配置内容如下:
server:
servlet:
context-path: /myapp这样在请求时就需要在请求时加入 /myapp 前缀作为请求. 即:
http://localhost:8080/users
变为
http://localhost:8080/myapp/users
2、继承路径
在springboot中同样支持使用继承的方式来实现自定义的路径,即一个子控制器类继承一个父控制器抽象类.
如下代码:
抽象类
package com.nodcat.api;
import org.springframework.web.bind.annotation.requestmapping;
@requestmapping("/api")
public abstract class absusercontroller {
}继承类
package com.nodcat;
import com.nodcat.api.absusercontroller;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.restcontroller;
@restcontroller
public class usercontroller extends absusercontroller {
@getmapping("/users")
public string user() {
return "hello, user!";
}
}这样我们就可以通过下面的请求获取用户:
http://localhost:8080/api/users
3、配置文件
如果要进行不同的包内所有类的路径的自定义配置,可以通过继承webmvcconfigurer自定义配置类的方式进行,代码如下:
package com.nodcat.config;
import org.springframework.context.annotation.configuration;
import org.springframework.web.servlet.config.annotation.pathmatchconfigurer;
import org.springframework.web.servlet.config.annotation.webmvcconfigurer;
import java.util.map;
@configuration
public class webmvcconfig implements webmvcconfigurer {
//app商家接口
//app消费者接口
//管理员接口
//开放接口
private final map<string, string> prefixtopackage = map.of(
"/app/merchant", "com.nodcat.api.app.merchant",
"/app/consumer", "com.nodcat.api.app.consumer",
"/admin", "com.nodcat.api.admin",
"/open", "com.nodcat.api.open"
);
@override
public void configurepathmatch(pathmatchconfigurer configurer) {
prefixtopackage.foreach((prefix, pkg) ->
configurer.addpathprefix(prefix, c -> c.getpackage().getname().startswith(pkg))
);
}
}通过上述配置,我们就对app商家接口,app消费者接口,管理员接口,开放接口进行前缀的区分,我们只需要在对应的包内实现对应的控制器就可以了. (在com.nodcat.api.admin包下的所有控制器路径都前缀都会加上/admin,即管理员的控制器)
疑问解答
直接通过继承的方式,在子类使用@requestmapping 可以实现路径拼接么?
不可以,在子类中使用@requestmapping会覆盖父类的@requestmapping的路径定义,路径不会被拼接.
总结
自定义路径可以通过[全局路径 继承路径 配置文件] 的方式进行,你可以在实际开发中按实际需要进行选择.
到此这篇关于springboot自定义请求前缀的代码步骤的文章就介绍到这了,更多相关springboot自定义请求前缀内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论