Spring-boot教程(一)整合Swagger

一、前言

Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件,它的源码地址在github上,源码地址:https://github.com/swagger-api/swagger-ui

建立一个简单的Springboot项目,不需要配置任何东西,只需要以下3个dependency

二、添加依赖

Swagger需要依赖两个jar包,在pom.xml中添加如下坐标

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

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

三、创建配置类

Swagger需要一个配置类来进行对swagger的基本配置

配置类:

@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //选择controller包
                .apis(RequestHandlerSelectors.basePackage("com.wqc.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //自定义信息可按需求填写
                .title("Spring Boot中使用Swagger构建RESTful APIs")
                .description("测试")
                .termsOfServiceUrl("http://www.duanxiaowei.top")
                .contact("wqc")
                .version("0.0.1")
                .build();
    }

}

四、启动类


@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

}

五、Controller

@Api("你好,世界")
@RestController
public class HelloWorldController {
    @ApiOpration("哈罗")
    @RequestMapping(value="/hello",method=RequestMethod.GET)
    public String index() {
        return "Hello World";
    }
}

六、测试

启动application 并访问http://localhost:8080/swagger-ui.html

猜你喜欢

转载自blog.csdn.net/wqc19920906/article/details/81543528