SpringBoot road (8) - Use Swagger2 let drop interface documentation and testing easier

Scenes

Brothers, on the one demonstrated how simple SpringBoot Restful Web development project ah, is simply simple to explode. Anyway, after my brother I spent SpringBoot, do not want to write is to write original Spring project with a bunch of configuration.

Who does not want simple things to do, good to have more time to accompany his girlfriend shopping to buy a skirt ah? What? You did not girlfriend, you do not want to have more time to play it good brothers, do not be so brain-dead line does not?

Seriously, find a girlfriend or is the right way!

Well, then we have Restful, the development of back-end API interface is really simple enough, but how to test the pinch.

To do the test, you have to realize the front-end engineering? It also separated the front and rear end Jiaosha it.

Do you want to use a separate test tools, such as Postman, tutor function quite full, but we did not know Postman items Editor's Note ah, URL parameters had to own one by one to fill, and more trouble ah.

Since we are placed in this program, and each interface URL address parameters are determined, it can not automatically generate visual interface test it, let's fill fill initiate test parameters on the line.

Swagger2 used is cool

Sure blanket, with Swagger2 that blanket. Not only is automatically generated visual test, also automatically generates the interface documentation.

When others to test directly see the document describes, not to ask you. The lazy programming principles to the limit.

Here mention that the program is to develop lazy enough to make feel the demand side: ye so easy, so easy to use pinch.

Implementation

Well, pull up a lot, to see how to achieve.

1, import-dependent

We still use the previous section of the Web project presentation, of course, you can use any of SpringBoot 2.x version of the project to add Swagger2 operation.

Then import Swagger2 related dependencies, so our project will be able to support Swagger2 blanket, specific dependencies are as follows:

	<!-- 添加swagger2相关功能 -->
   	<dependency>
   		<groupId>io.springfox</groupId>
   		<artifactId>springfox-swagger2</artifactId>
   		<version>2.9.2</version>
   	</dependency>
   	<!-- 添加swagger-ui相关功能 -->
   	<dependency>
   		<groupId>io.springfox</groupId>
   		<artifactId>springfox-swagger-ui</artifactId>
   		<version>2.9.2</version>
   	</dependency>

TIPS: Why use 2.9.2 version? Because the 2.9.2 is the latest version, cool chant!

2, arranged to add class Swagger2

Swagger2 related functions can be configured, via configuration classes relevant points we have put the comments. It should be noted, do not find it hard to understand that this is a people defined class libraries, in fact, as long as we take over with the line, Swagger2 focus is to use on OK.

@Configuration // 告诉Spring容器,这个类是一个配置类,Spring容器得采用这个类的配置
@EnableSwagger2 // 启用Swagger2功能
public class Swagger2Config {
	/**
	 * 配置Swagger2相关的bean
	 */
	@Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
    			.apis(RequestHandlerSelectors.basePackage("com"))//com包下所有API都交给Swagger2管理
                .paths(PathSelectors.any())
                .build();
    }
	/**
	 * 此处主要是API文档页面显示信息
	 */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("演示项目API")   //标题
                .description("学习Swagger2的演示项目") //描述
                .termsOfServiceUrl("http://www.forwhatsogood.com") //服务网址,此处是我个人网站地址
                .version("1.0") //版本
                .build();
    }
}
3, configure a static resource access

Since Swagger2 relevant API documentation html / css / js pages, and SpringBoot 2.x default intercepts static resources, we need to configure static resources through configuration class.

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 允许一下目录静态资源访问
		registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
		registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
	}
}

4, start the project and view, test

Start the project, in an address before the visit http://127.0.0.1:1007later added /swagger-ui.htmlthat access http://127.0.0.1:1007/swagger-ui.html.

Shown below, we can see our weight controller API methods are listed.

image description

Click on one of the API, then click try it out, you can automate the injection parameters and displays the results, as shown below, we all try on OK.
image description

5, automatically generate API documentation notes

By adding annotation on the controller, document content can be generated in Swagger page, modify controller code as follows:

@Api(tags = "博客API") // 类文档显示内容
@RestController // 通过该注解,第一将BlogController注册为控制器,第二将其中方法返回值转换为json
public class BlogController {
   @Autowired // 自动装配blogService
   private BlogService blogService;

   @ApiOperation(value = "根据id获取博客信息") // 接口文档显示内容
   @GetMapping("/blog/{id}")
   public BlogDo getOne(@PathVariable("id") long id) {
   	return blogService.getBlogById(id);
   }

   @ApiOperation(value = "获取博客列表") // 接口文档显示内容
   @GetMapping("/blog")
   public List<BlogDo> getList() {
   	return blogService.getBlogList();
   }

   @ApiOperation(value = "新增博客") // 接口文档显示内容
   @PostMapping("/blog")
   public void add(@RequestBody BlogDo blog) {
   	blogService.addBlog(blog);
   }

   @ApiOperation(value = "根据id修改博客信息") // 接口文档显示内容
   @PutMapping("/blog/{id}")
   public void update(@PathVariable("id") long id, @RequestBody BlogDo blog) {
   	// 修改指定id的博客信息
   	blog.setId(id);
   	blogService.updateBlog(blog);
   }

   @ApiOperation(value = "根据id删除博客") // 接口文档显示内容
   @DeleteMapping("/blog/{id}")
   public void delete(@PathVariable("id") long id) {
   	blogService.deleteBlog(id);
   }
}

After adding api annotations, Swagger page shown below, is very clear and easy API documentation and debugging can click, pay close attention to try it.
image description

to sum up

Swagger2 test than to write front-end code debugging, or write Java Http code debugging, debugging or by Postman and other tools are easy to use.

Because you do not write code, visualization, parameter is automatically generated, we only need to fill in the parameters can be specified parameter location.

Certainly not a panacea, such as batch testing, concurrency testing, this tool is not playing.

So Swagger usage scenario is as API documentation, or developers to adjust the parameters of the test after the completion of the logical correctness.

Published 397 original articles · won praise 270 · views 550 000 +

Guess you like

Origin blog.csdn.net/woshisangsang/article/details/104617083
Recommended