In Spring MVC, Swagger2 is used to build a dynamic RESTful API.

Source: Internet
Author: User

In Spring MVC, Swagger2 is used to build a dynamic RESTful API.

When multiple terminals (WEB/mobile terminals) require public service logic, a RESTful service is generally built for multiple terminals.

To reduce frequent communication costs with the corresponding terminal development team, we will create a RESTful API document to record all interface details at the beginning.

However, as the project progresses, the problems exposed in this way become more and more serious.

A. many interfaces and complicated details (different HTTP request types, HTTP header information, and HTTP request content must be considered ..), it is very difficult to create this document with high quality.

B. The interface document must be modified synchronously when the interface implementation is constantly modified, and the document and code are in two different media. unless there is a strict management mechanism, it will easily lead to inconsistency.

Based on this, the project team introduced Swagger in earlier times. After several projects have been accumulated, it has indeed achieved good results.

Swagger is a standardized and complete framework for generating, describing, calling, and visualizing RESTful Web Services.

The service methods, parameters, and models are closely integrated into the server code, so that the maintenance documents and adjustment code are integrated, so that the API is always synchronized.

This article mainly describes the process of integrating Swagger with SpringMVC and some problems encountered. We can only use it for discussion and analyze specific projects.

1. Maven dependency and simplest Configuration
      <!--restfull APi swagger2-->        <dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox-swagger2</artifactId>            <version>${swagger.version}</version>        </dependency>        <dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox-swagger-ui</artifactId>            <version>${swagger.version}</version>        </dependency>

Spring-Context Swagger Configuration:

<! -- Swagger2 configuration class --> <bean id = "config" class = "com. rambo. spm. core. config. SwaggerConfig"/> <! -- Swagger2 static resources are managed by spring ing (springfox-swagger-ui.jar is a static resource package) --> <mvc: resources mapping = "swagger-ui.html" location = "classpath: /META-INF/resources/"/> <mvc: resources mapping ="/webjars/** "location =" classpath:/META-INF/resources/webjars/"/>

<Mvc: resources/> Spring MVC processes static resources and adds some useful value-added functions.

A. <mvc: resources/> allows static resources to be placed anywhere, such as under the WEB-INF directory, class path, etc., completely breaking the limit that static resources can only be placed under the root path of the Web container.

B. <mvc: resources/> optimize static resources based on the famous browser optimization principles such as Page Speed and YSlow.

SwaggerConfig configuration class:

@ Configuration @ EnableSwagger2public class SwaggerConfig {@ Bean public Docket createRestApi () {return new Docket (DocumentationType. SWAGGER_2 ). apiInfo ()). select (). apis (RequestHandlerSelectors. withMethodAnnotation (ApiOperation. class )). paths (PathSelectors. any ()). build ();} private ApiInfo apiInfo () {ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder (); apiInfoBuilder. title ("SPM Doc"); apiInfoBuilder. description ("SPM Api documentation"); apiInfoBuilder. contact (new Contact ("orson", "https://www.cnblogs.com/", ""); apiInfoBuilder. version ("2.0"); return apiInfoBuilder. build ();}}

Which Request Method APIs are generated? Swagger provides the RequestHandlerSelectors object using the following methods:

2. Service annotation configuration practices

After the above operations, Swagger has been integrated. in the project development process, you only need to add the corresponding annotation on the corresponding RESTful service.

@ Api: annotation indicates the role of the class on the class. You can mark a Controller class as a swagger document resource. Usage:

@ Api (description = "user management ")

@ ApiOperation: The annotation describes the function of a method on the method. The definition of each url resource is as follows:

@ ApiOperation (value = "getting all users ")

@ ApiParam and @ ApiImplicitParam: annotate the parameter to describe the role of the parameter. Usage:

@ ApiParam (value = "User ID") String userId

The above are the simplest configurations. It is enough to build clear API documents. Of course, there are also a lot of annotations. You just need to know.

@ RestController @ Api (description = "user management") public class UserRestController extends BaseController {@ Autowired private SysUserService sysUserService; @ GetMapping ("r/user/get ") @ ApiOperation (value = "Get specific user details") public Object getUser (ModelMap modelMap, @ ApiParam (value = "User ID") String userId) {}@ PostMapping ("r/user/add") @ ApiOperation (value = "add user") public Object addUser (ModelMap modelMap, @ ModelAttribute @ Valid SysUser user, BindingResult result) {}}

Problems encountered in subsequent use of the project:

A. Some method input parameters, such as HttpServletRequest, HttpServletResponse, HttpSession, and ModelMap, are meaningless when these parameters are generated in the API documentation. Is Swagger correctly configured?

At the beginning, use @ ApiParam (hidden = true) to annotate these parameters. When there are many methods, write these types of input parameters again, which is redundant.

In the API, it is found that the Docket object has the ignoredParameterTypes method. You can define the ignored parameter types in the configuration class, which is much easier.

public Docket createRestApi() {        return new Docket(DocumentationType.SWAGGER_2)                .apiInfo(apiInfo())                .ignoredParameterTypes(ModelMap.class, HttpServletRequest.class,HttpServletResponse.class, BindingResult.class)                .select()                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))                .paths(PathSelectors.any())                .build();    }

B. How do I annotate a request with a encapsulated object? How to annotate attributes in an object? How does one block the mo attributes in an object?

When the request parameter is an object, the Spring @ ModelAttribute annotation is used to annotate the corresponding object. The attribute in the object uses @ ApiModelProperty to shield the attribute @ ApiModelProperty (hidden = true)

@ ApiModelProperty (hidden = true) private String uuid; @ ApiModelProperty ("name") private String name; @ ApiModelProperty ("password") private String passwd;

Swagger has many tools and can do many things. This article only allows you to quickly learn about it, use it, check more information, and read more blogs.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.