[Turn] article takes you to get to know SpringBoot integration with Swagger

https://blog.csdn.net/itguangit/article/details/78978296

Swagger use

由于不喜欢csdn的markwoen编辑器,对代码样式支持不好,看着不舒服,对审美要求比较高的同学移步github:https://github.com/itguang/swagger/tree/master/springboot-swagger-demo1

不知道怎么调整csdn的代码样式,有高人知道,请私信我一下.

Swagger What's the use?

swagger is a popular API development framework that in order to "open API declarations" (OpenAPI Specification, OAS), based
on the development cycle throughout the API provides the appropriate solution is a very large project (including design, coding and testing, almost all languages are supported).

Swagger is a standardized and complete framework for generating, description, and visualization calls for RESTful Web services.
The overall objective is to make the client and the file system as a server at the same rate updates.
Methods, parameters and models are tightly integrated into the file server-side code that allows the API to always be in sync. Swagger allow management to deploy and use powerful API has never been easier.

springfox general principle:

general principle springfox is, the project start over species, spring context in the initialization process,
framework automatically with data configured to load some swagger related bean to the current context, and automatically scans the system may need to be generated api documentation of those classes ,
and generates the corresponding cached information. If the project MVC controlling layer is then automatically scan all springMvc Controller class, and generates description data corresponding to the document.

The json data format, through the path: LOCATION / v2 / api-docs access to the data, and generate the corresponding document describes swaggerUI interface according to this data.
Because we can get this data, so we can generate your own page.
SpringBoot and Swagger2

Due to the powerful annotation features java, we use SpringBoot to combine Swagger2, in a very simple to use.
Because of the popular Spring, Marty Pitt wrote a Spring-based component swagger-springmvc, for integration into the swagger springmvc in the past.
The first step: New SpringBoot project, the introduction of dependency.


io.springfox
springfox-swagger2
2.7.0

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.7.0</version>
    </dependency>

1
2
3
4
5
6
7
8
9
10
11
12

The above two effects rely on:

springfox-swagger2 is still dependent OSA specification document, which is a json file API description, but the function of this component is to help us to automatically generate the json file,
springfox-Swagger-ui is to parse out the json file, in a more friendly manner presented.
Step 2: Create api

/**

  • @author itguang
  • @create 2018-01-05 8:23
    **/
    @RestController
    public class UserController {

    @RequestMapping("/hello",method = RequestMethod.GET)
    public String hello(){
    return "hello";
    }

}

1
2
3
4
5
6
7
8
9
10
11
12
13

Configuration Swagger2

Now Swagger2 not generate API documentation for us, because we do not have to configure it.

We need to create a configuration class, as follows:

/**

  • @author itguang
  • @create 2018-01-04 13:36
    **/
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig{

    @Bean
    public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
    .apiInfo(apiInfo())
    .select()
    .apis(RequestHandlerSelectors.basePackage("com.itguang.springbootswaggerdemo1.web"))
    .paths(PathSelectors.any())
    .build();
    }

    private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
    .title("Spring Boot中使用Swagger2构建RESTful API")
    .description("rest api 文档构建利器")
    .termsOfServiceUrl("http://blog.csdn.net/itguangit")
    .contact("itguang")
    .version("1.0")
    .build();
    }

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

springfox provides us with a Docket (summary of the meaning) class, we need to make it a Bean injected into the spring,
obviously, we need a configuration file, and by a way (obviously it would be a comment) tells the program this is a Swagger profile.

springfox allows us to combine information into a ApiInfo class as a constructor parameter to the Docket (of course, can not construct this class, and the direct use of null, but you of this API is too low a).
Get

Now we have to do configuration has been able to meet the basic requirements of a generated API documentation, let us start the project, visit: http: //localhost/swagger-ui.html

You will see the following interface:

This is Swagger-ui interface generated for us.
Swagger2 use annotations

Next, we will carefully study notes under springfox-swagger2 for us to offer.

We create a Controller, the User class is used to perform common CRUD operations,

/**

  • @author itguang
  • @create 2018-01-04 13:31
    **/

@RestController
@RequestMapping (value = "/ User", Produces = APPLICATION_JSON_VALUE) // Return Value Configuration file application / JSON
@Api (Description = "User Management")
public class HelloController in {

ArrayList<User> users = new ArrayList<>();


@ApiOperation(value = "获取用户列表", notes = "获取所有用户信息")
@RequestMapping(value = {""}, method = RequestMethod.GET)
public List<User> hello() {
    users.add(new User("逻辑", "luoji"));
    users.add(new User("叶文杰", "yewenjie"));
    return users;
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

You can see that we use @Api (description = "User Management") notes on the Controller, using @ApiOperation in approach (value = "get a list of users", notes = "Get all User Information") notes,

? What effect this will have to raise it again next visit we can try ah:

We can see the red box framed it in place has changed, and it is amazing that we automatically determine the return type:

[
{
"age": 0,
"email": "string",
"enabled": true,
"id": "string",
"password": "string",
"username": "string"
}]

1
2
3
4
5
6
7
8
9
10

? But if we want to selectively ignore a field, rather than all the fields in the User class exposes the go do not worry, we can use another annotation: @ApiModelProperty (hidden = true)

This annotation can be applied to the field or method, as long as the hidden attribute is true, the field or method would not be generated api documentation.

as follows:

/**

  • @author itguang
  • @create 2017-12-30 14:39
    **/
    @Data
    public class User {

    private String id;

    private String username;

    @ApiModelProperty(hidden = true)
    private String password;

    private String email;

    private Integer age;

    private Boolean enabled;

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

We deliberately ignore the password field, refresh your browser again, you will see:

Indeed password field is gone.

Next we created a simulated user api:

@ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
@RequestMapping(value = "/create", method = RequestMethod.POST)
public User postUser(User user) {

    return user;
}

1
2
3
4
5
6

We can see that we need to pass the client a User object for the user to create and here we do nothing, just received the User object returned to the client, to represent successfully created.

We look to refresh your browser:

You can not see the request parameters so we are very satisfied with the ah, the first no field descriptions, first some fields when creating a user ah we do not need, or do not worry, we have a solution:

@ApiModelProperty(hidden = true)
private String id;

@ApiModelProperty(value = "用户名")
private String username;

@ApiModelProperty(value = "密码")
private String password;
@ApiModelProperty(value = "邮箱")
private String email;

@ApiModelProperty(hidden = true)
private Integer age;

@ApiModelProperty(hidden = true)
private Boolean enabled;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

We add the User object in the field of the above comments: @ApiModelProperty (hidden = true) and @ApiModelProperty (value = "username")
value attribute specifies the meaning of the fields (description Description), refresh your browser to try again:

How, it is not very simple.

Here we look at how to pass parameters: add a method to obtain information based on user id

@ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
@RequestMapping(value = "getUser/{id}", method = RequestMethod.GET)

public User getUser(
                    @PathVariable(value = "id") String id) {

    return new User(id, "itguang", "123456");
}

1
2
3
4
5
6
7
8

Refresh your browser to see

We need to pass a client parameter id, id now we give this parameter a description (Description), which we supposed to do or do not worry, it can be simple like this?:

@ApiOperation (value = "get user details", notes = "details as to obtain the user's id url")
@RequestMapping (value = "the getUser / {ID}", = RequestMethod.GET Method)

public User getUser(@ApiParam(value = "用户id", required = true) //[注意] @ApiParam与 Controller中方法并列使用,也可以省略的
                    @PathVariable(value = "id") String id) {

    return new User(id, "itguang", "123456");
}

1
2
3
4
5
6
7
8

We've added @ApiParam (value = "user id", required = true) this annotation, note that the foregoing parameters of this annotation method can not be used directly in the above methods.
Refresh your browser again:

Common explanatory notes:

Through the above understanding, we will probably have to use Swagger2, but we only introduce some simple common notes, let's summarize the system:
Swagger2 basic use (bold emphasis):

@Api: 描述类/接口的主要用途

@ApiOperation: 描述方法用途

@ApiImplicitParam: 描述方法的参数

@ApiImplicitParams: 描述方法的参数(Multi-Params)

    可以在上面 创建用户的方法上添加 @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")试试看.

@ApiParam:请求属性

@ApiIgnore: 忽略某类/方法/参数的文档

    注意与 @ApiModelProperty(hidden = true)不同, @ApiIgnore 不能用在模型数据上

@ApiResponse:响应配置

    如: @ApiResponse(code = 400, message = "无效的用户信息") ,注意这只是在 生成的Swagger文档上有效,不要和实际的客户端调用搞混了.
    通常我们都是统一JSON返回,用不到这个注解

@ApiResponses:响应集配置

@ResponseHeader: 响应头设置

    例如: @ResponseHeader(name=”head1”,description=”response head conf”)

@ApiModelProperty:添加和操作模型属性的数据

I want to see the Chinese

After the above introduction, you will have to use Swagger2, but for some people, see above English representation very hard to accept, there is no Chinese?

Have!

Follow the prompts on official documents, and replace interface language in springboot is very simple, first of all we need to have an understanding of SpringBoot resource directory:

Spring Boot default "agreement" Read static resources from these subdirectories resource directory:

src/main/resources/META-INF/resources
src/main/resources/static (推荐)
src/main/resources/public

1
2
3

For chestnut: There is a picture under static directory, kumamon.jpg

Access address: http: // localhost: 8080 / img / kumamon.jpg

Note: If the directory contains the same path different static pictures, press on the priority, the highest META-INF / resources directory priority.

SpringBoot understand the priority of the resource directory, let's look at springfox-swagger-ui package introduced before, open maven depend find it:

Expand as follows:

Why do we remember before the browser input http: //localhost/swagger-ui.html will see a page you Swagger, yes it is here,

Home is where the swagger-ui.html,

Open look:

<!DOCTYPE html>



Swagger UI




















 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

I can not read? Well, do not understand it does not matter, we want the finished we supposed to do?

We can not directly modify the source code here, ah, remember priority Spring boot directory of resources we mentioned earlier it? Yes, we just need to create the META-INF directory of the resource in the project on the line ah remember,

Spring boot default will our project src / main / resources / META- INF / resources covered under other file dependency.
Begin Speaking

Create a resource directory src / main / resources / META-INF / resources, as follows:

swagger-ui.html reads as follows:

<!DOCTYPE html>



itguang






<script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>

<!--国际化操作:选择中文版 -->
<script src='webjars/springfox-swagger-ui/lang/translator.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lang/zh-cn.js' type='text/javascript'></script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

In fact, we only add two lines of code:



1
2
3

zh-cn.js document reads as follows:

'use strict';

/ * Jshint quotmark: Double * /
window.SwaggerTranslator.learn ({
"Warning: of Deprecated": "Warning: Obsolete",
"Implementation the Notes": "to realize Remarks",
"the Response Class": "response type",
"the Status ":" status ",
" the parameters ":" parameters ",
" the parameter ":" parameters ",
" the value ":" value ",
" the description ":" description ",
" the parameter the type ":" parameter type ",
" the Data type ":" data type ",
" the messages the response ":" a response message ",
" the HTTP the status code ":" the HTTP status code ",
" reason ":" reason ",
" the model the response ":" response model ",
"Request URL ":" requests the URL ",
" the Request Headers ":" request header ",
" the Response Body ":" in response to the body ",
" the Response Code ":" response code ",
" the Response Headers ":" response header ",
" Hide response ":" hidden response ",
" Headers ":" head "
"Try it out!": "Try!",
"Show / Hide": "Show / Hide",
"List the Operations": "Display Operation",
"Expand the Operations": "Expand Operation",
"Raw": " original ",
." CAN not the parse JSON raw the result ":" unable to parse JSON original result ",.
" example value ":" example ",
" the click to the sET AS the parameter value ":" click set parameters ",
" Model Schema ":" model architecture ",
" model ":" model ",
" the apply ":" application ",
" the username ":" username ",
" password ":" password ",
" Terms of service ":" Terms of service " ,
"the created by": "creator,"
"See more at ":" View more: ",
" Business Card at The Developer ":" Contact developer ",
" API Version ":" API version ",
" the Response Content Type ":" Type response Content ",
" the Parameter Content of the type : ":" parameter types: "
" fetching resource ":" Getting resources "
"fetching resource list": "Getting Resource List",
"Explore": "Browse",
"Show Swagger Petstore Example Apis": "Swagger Petstore show an example of Apis",
"of Can not Server from the Read It May not have have at The. appropriate access-control-origin settings. ":" unable to read from the server may not be set correctly access-control-origin ",..
" Please at the protocol for the specify ":" Please specify the agreement: ",
" the read Swagger of Can not JSON from ":" unable to read swagger JSON in ",
" Finished resource information loading Swagger rendering the UI. ":" loaded resource information that is rendering the UI Swagger ",.
" unable to the read API ":" unable to read api ",
"from path": "from the path",
"server returned": "server returns"
});

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

You can also define your own Chinese name it.
Speaking get.

This, of swagger finished work has been done, is not very simple, restart the project, visit http: //localhost/swagger-ui.html you can see that the document has been completely finished it:

summary:

Well, on Swagger2 Tutorial in the project on here.

Source Download: https://github.com/itguang/swagger/tree/master/springboot-swagger-demo1

Author: PostTruth
Source: CSDN
Original: https: //blog.csdn.net/itguangit/article/details/78978296
Copyright: This article is a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin www.cnblogs.com/wincai/p/11287118.html