Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Swagger Doc Registration with arbitrary Architecture in Swagger extension Development

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the Swagger extension development of any architecture to achieve Swagger Doc registration example analysis, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Origin: the company's old project before 2008 was followed by an iterative version, and the architecture was too old to work on its own. So I proposed to upgrade to SpringBoot, a new one that would feel better. But there are too many old interfaces, which are implemented by custom Servlet and called by scanning Bean function through reflection. Also do not want to change all the interfaces to the new, the old interface front-end to Swagger there is no way, on the scalp.

Checked a lot of data, are SpringBoot integrated Swagger, repetitive, simple technical content is very low, did not find what I want.

First of all, the project is integrated, refactoring supports SpringBoot, starts through SpringBoot, and integrates Swagger, and the newly written RESTAPI supports Swagger. Now you need to scan the old interface to generate Swagger.

Implement a Spring ApplicationListener that is called after Spring ApplicationContext initialization is completed to generate a Swagger scan of the old interface.

@ Repositorypublic class SwaggerExtentionSupport implements ApplicationListener {@ Override public void onApplicationEvent (ContextRefreshedEvent event) {/ / Spring framework is loaded completely, scan bean to get servlet initSwagger (event.getApplicationContext ());}}

Inject DocumentationCache

@ AutowiredDocumentationCache documentationCache;// Swagger defaults to Default. For the interface, we put @ Value ("${swagger.group}") private String groupName under the custom group.

Through Debug, the newly implemented SpringBoot interface is found, which is constructed as follows:

Start scanning interface

Private void initSwagger (ApplicationContext context) {Documentation documentation = documentationCache.documentationByGroup (groupName); if (documentation = = null) {/ / if not specified by groupName, mount documentation = documentationCache.documentationByGroup (Docket.DEFAULT_GROUP_NAME) on default;} if (documentation! = null) {/ / get all API collections Multimap apiListings = documentation.getApiListings () Class [] clazzs =. / / Scan Classes for (Class aClass: clazzs) {log.info ("add swagger bean {}", aClass.getSimpleName ()); Method [] servletMethods = aClass.getDeclaredMethods (); for (Method servletMethod: servletMethods) {String methodName = servletMethod.getName () / / get the interface name, which must conform to the API interface, and the method is public if (validSwagger (methodName) & & Modifier.isPublic (servletMethod.getModifiers () {/ / return tags Set tags = addApi (apiListings, documentation.getBasePath (), name, methodName) If (! tags.isEmpty ()) {documentation.getTags () .addAll (tags);} log.info ("swagger apis size: {}", apiListings.size ());}

Add the scan to the Swagger legally

Private Set addApi (Multimap apiListings, String basePath, String beanName, String methodName) {/ / get the name and remove the suffix String optGroup = getName (beanName); String apiId = optGroup + "_" + methodName; / / globally unique String optId = methodName / / use apiID to check whether it is unique, and then add Collection apis = apiListings.get (apiId) to the same tag; if (apis = = null) {/ / only use the size of apis to get the length apis = new HashSet ();} ArrayList apis1 = new ArrayList (); ArrayList operations = new ArrayList (); ResponseMessage v200 = new ResponseMessageBuilder (). Code (200). Message ("OK"). Build () ResponseMessage v401 = new ResponseMessageBuilder (). Code (401). Message ("Unauthorized"). Build (); ResponseMessage v403 = new ResponseMessageBuilder (). Code (403). Message ("Forbidden"). Build (); ResponseMessage v404 = new ResponseMessageBuilder (). Code (404). Message ("Not Found"). Build (); / / tag,Swagger home page shows the interface HashSet tags = new HashSet () mounted under tag,tag / / description is the filename of the generated API JS / / optGroup is the generated function name Tag tag = new Tag (optGroup, optGroup + "Controller"); tags.add (tag); / / leave the parameter ArrayList parameters = new ArrayList () for the time being. / / Note position. It must be a value that does not repeat. The value 0 / Operation only needs tag name. He decided that tag Operation operaGet = new Operation (HttpMethod.GET, "do exec" + optGroup + "." + methodName, "new ModelRef (" string "), optId+" UsingGET ", 0, Sets.newHashSet (tag.getName ()) mounted on the Swagger Sets.newHashSet (MediaType.ANY_TYPE.toString ()), Sets.newHashSet (MediaType.create ("application", "json"). ToString (), newHashSet (), new ArrayList (), parameters, Sets.newHashSet (v200, v401, v403, v404), ", false New ArrayList () Operations.add (operaGet); / / operations.add (operaPost); String url = "/" + beanName+ "? invoke=" + methodName; apis1.add (new ApiDescription (groupName, url, beanName+ "." + methodName, operations, false)) / / Note position. It must be a value that does not repeat. Here I use apis.size () ApiListing apiListing = new ApiListing (API_VER, basePath, "/" + beanName, new HashSet (), new HashSet (), ", new HashSet (), new ArrayList (), apis1, new HashMap (), beanName+". "+ methodName, apis.size (), tags). / / put apiListings.put (apiId, apiListing) in the api list; / / return tag,tag will be displayed to Swagger Content return tags;}

Generate Swagger effects such as:

Swagger extension development on any architecture to achieve Swagger Doc registration example analysis is shared here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report