SpringBoot动态生成接口
admin
2024-05-09 20:41:15
0

SpringBoot动态生成接口

文章目录

  • SpringBoot动态生成接口
  • 一,简单例子
  • 二,各种请求方法以及条件
    • 2.1 无参GET方法
    • 2.2 带1参的GET方法
    • 2.3 带多参的GET方法
    • 2.4 无参POST方法
    • 2.5 带参POST方法
    • 2.6 Body带数据的POST方法
  • 三,运行时生成接口

最近遇到一个需求,需要在程序运行过程中,可以动态新增接口,自定义接口参数名称,基本类型,以及请求方法,请求头等等。通过几天的研究,找到了我需要的解决方案。

对于这个需求,我首先要研究的是程序是怎么加载非@Controller/@RequestMapping等等注解下的接口,然后发现加载接口都需要被RequestMappingInfo处理,可以通过该类进行动态接口生成。

一,简单例子

首先,我要做一件最简单的事,就是在程序运行时加载一个我自定义的接口,具体代码如下:

@SpringBootApplication
public class ServiceApiApplication {public static void main(String[] args) throws NoSuchMethodException {ApplicationContext application = SpringApplication.run(ServiceApiApplication.class, args);RequestMappingHandlerMapping bean = application.getBean(RequestMappingHandlerMapping.class);RequestMappingInfo requestMappingInfo = RequestMappingInfo.paths("/lmcTest").methods(RequestMethod.GET).build();bean.registerMapping(requestMappingInfo, "adapterController", AdapterController.class.getDeclaredMethod("myTest"));}

AdapterController.java

/*** @ClassName: AdapterController* @author: Leemon* @Description: TODO* @date: 2021/12/23 10:14* @version: 1.0*/
@RestController
@Slf4j
public class AdapterController {Object myTest() {return "this is test request";}}

运行程序后,访问接口 http://localhost:8070/lmcTest,可以正常访问到接口内容,结果如下:

this is test request

二,各种请求方法以及条件

刚才的例子是一个最简单无参的get请求,但实际需求中我们的接口可能带有参数等等不同的需求。对于各种条件下的动态接口,如下所示

2.1 无参GET方法

		// 无参get方法RequestMappingInfo requestMappingInfo = RequestMappingInfo.paths("/lmcTest").methods(RequestMethod.GET).build();bean.registerMapping(requestMappingInfo, "adapterController", AdapterController.class.getDeclaredMethod("myTest"));

请求举例: http://localhost:8070/lmcTest

2.2 带1参的GET方法

        // 带一参数的get方法RequestMappingInfo requestMappingInfo1 = RequestMappingInfo.paths("/lmcTest2").params(new String[]{"fileName"}).methods(RequestMethod.GET).build();bean.registerMapping(requestMappingInfo1, "adapterController", AdapterController.class.getDeclaredMethod("myTest2", String.class));

AdapterController.java

	Object myTest2(@RequestParam("fileName") String value) {return "this is my param : " + value;}

	Object myTest2(String fileName) {return "this is my param : " + fileName;}

请求举例:http://localhost:8070/lmcTest2?fileName=hhh

结果如下:

this is my param : hhh

2.3 带多参的GET方法

        // 带多个参数的get方法RequestMappingInfo requestMappingInfo2 = RequestMappingInfo.paths("/lmcTest3").params(new String[]{"fileName", "type", "isSort"}).methods(RequestMethod.GET).build();bean.registerMapping(requestMappingInfo2, "adapterController", AdapterController.class.getDeclaredMethod("myTest3", String.class, String.class, Boolean.class));

AdapterController.java

	Object myTest3(String fileName, String type, Boolean isSort) {JSONObject jsonObject = new JSONObject();jsonObject.put("fileName", fileName);jsonObject.put("type", type);jsonObject.put("isSort", isSort);return "values : " + jsonObject.toJSONString();}

请求举例:http://localhost:8070/lmcTest3?fileName=hhh&isSort=false&type=KKK

结果如下:

values : {"isSort":false,"fileName":"hhh","type":"KKK"}

2.4 无参POST方法

		// 无参post方法RequestMappingInfo requestMappingInfo3 = RequestMappingInfo.paths("/lmcTest4").methods(RequestMethod.POST).build();bean.registerMapping(requestMappingInfo3, "adapterController", AdapterController.class.getDeclaredMethod("myTest"));

请求举例: POST http://localhost:8070/lmcTest4

结果与2.1相同

2.5 带参POST方法

        // 带参post方法RequestMappingInfo requestMappingInfo4 = RequestMappingInfo.paths("/lmcTest5").params(new String[]{"fileName", "type", "isSort"}).methods(RequestMethod.POST).build();bean.registerMapping(requestMappingInfo4, "adapterController", AdapterController.class.getDeclaredMethod("myTest3", String.class, String.class, Boolean.class));

请求举例: POST http://localhost:8070/lmcTest5?fileName=hhh&isSort=false&type=KKK

结果与2.3相同

2.6 Body带数据的POST方法

        // body带参的post方法RequestMappingInfo requestMappingInfo5 = RequestMappingInfo.paths("/lmcTest6").produces(new String[]{"text/plain;charset=UTF-8"}).methods(RequestMethod.POST).build();bean.registerMapping(requestMappingInfo5, "adapterController", AdapterController.class.getDeclaredMethod("myTest4", HttpServletRequest.class));System.err.println("已经加载/lmcTest");

AdapterController.java

    Object myTest4(HttpServletRequest request) {byte[] body = new byte[request.getContentLength()];JSONObject json = null;try (ServletInputStream in = request.getInputStream();) {in.read(body, 0, request.getContentLength());json = JSON.parseObject(new String(body, "UTF-8"));} catch (IOException e) {e.printStackTrace();}if (Objects.isNull(json)) {return "fail to parse request";}return String.format("name is %s and age is %s", json.getString("name"), json.getString("age"));}

请求举例:POST http://localhost:8070/lmcTest6

请求体JSON:

{"name":"kkk","age":12
}

结果如下:

name is kkk and age is 12

三,运行时生成接口

前面介绍了几种动态接口生成方式,下面我将介绍一下调用一个接口,来生成新接口的场景

AdapterController.java

    @GetMapping("create")public String create() throws NoSuchMethodException {RequestMappingHandlerMapping bean = applicationContext.getBean(RequestMappingHandlerMapping.class);// 无参get方法RequestMappingInfo requestMappingInfo = RequestMappingInfo.paths("/leenai").methods(RequestMethod.GET).build();bean.registerMapping(requestMappingInfo, "adapterController", AdapterController.class.getDeclaredMethod("myTest"));return "success to create and reload createRestApi()";

运行后访问接口: http://localhost:8070/create,会生成一个新接口 http://localhost:8070/leenai

访问结果如2.1所示

前面几种方式都调试成功后,基本上可以自己自定义大部分的接口了。动态接口生成之后,可以存储到数据库中,等到下一次或者新集群实例发布时,直接就可以引用了。

这是我找到的一种动态生成接口方式,不明确有没有更优解。

在我的实际需求中,动态接口生成之后还要被Swagger发现,可能这也是比较常见的使用方式,我将在下篇文章再来介绍我的处理过程。

相关内容

热门资讯

“五角大楼继续增兵中东,美以或... 据央视新闻 俄罗斯方面14日披露的来自俄联邦安全会议消息,鉴于五角大楼继续增兵中东地区,美国和以色列...
特朗普:我对她感到震惊 特朗普:对意大利总理“不帮助美国”表示震惊 据意大利方面14日消息,美国总统特朗普对意大利总理梅洛尼...
国台办:赖清德当局不管编列多少... 【环球网报道】4月15日上午,国台办举行例行新闻发布会,发言人陈斌华就近期两岸热点问题回答记者提问。...
美军已迫使六艘离开霍尔木兹海峡... 参考消息网4月15日报道据美国《华盛顿邮报》网站4月14日报道,美国军方官员14日表示,在特朗普政府...
朝鲜外务省:日本《外交蓝皮书》... 当地时间4月14日,朝鲜外务省日本研究所政策室长发表谈话说,日本政府日前发布的2026年版《外交蓝皮...
“美国不再可靠,德国转向法国:... 【文/观察者网 王一】 美国总统特朗普退出北约的威胁,让欧洲盟友觉得美国愈发不可靠,正加快制定北约...
距中国台湾仅110公里!日本计... 据央视新闻,日本冲绳县与那国町町长13日表示,他同意日本防卫省此前提出的计划——在与那国町部署防空导...
四川首个微短剧审核服务点在青羊... 第十三届中国网络视听大会于4月14日-16日在成都举办,国内头部微短剧平台点众科技将亮相本次大会。在...
伊朗:战争赔偿是伊美谈判议题,... 新闻荐读 据伊朗伊斯兰共和国通讯社14日报道,伊朗政府发言人穆哈杰拉尼表示,战争赔偿问题是伊朗与美国...
大批“五一”航班突然取消?最新... 澎湃新闻记者 邵冰燕 五一假期临近,不少准备出境旅游的旅客遭遇航班变动。多位网友在社交平台上发文称,...