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

具体实现操作:

一,添加依赖

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>

二,创建配置类

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.shsxt.controller"))
                .paths(PathSelectors.any())
                .build();
    }

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

}

 

启动类:

@Controller
@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private User user;

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

    @Override
    public void run(String... strings) throws Exception {
        System.out.println(user.getUserId());
    }
}

 

三,启动并访问

 

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

 

 

 

四,额外配置(非必需)

最常用的5个注解 主要用来对接口或参数做备注信息

@Api:修饰整个类,描述Controller的作用

@ApiOperation:描述一个类的一个方法,或者说一个接口

@ApiParam:单个参数描述

@ApiModel:用对象来接收参数

@ApiProperty:用对象接收参数时,描述对象的一个字段

 


@Api(value="用户模块")
@RestController
@RequestMapping("user")
public class UserController {
    
    @Autowired
    private UserService userService;

    @ApiOperation(value = "根据用户id查询用户")
    @GetMapping("find/{id}")
    public User findById(@PathVariable Integer id) {
        User user = userService.findById(id);
        return user;
    }
    @ApiOperation(value = "修改用户信息")
    @PutMapping("update")
    public String update(User user) {
        return "更新成功";
    }
    @ApiOperation(value = "添加用户")

    @PostMapping("add")
    public String add( User user) {
        return "添加成功";
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("delete/{id}")
    public String delete(
            @ApiParam(required=true, name="ID", value="编号")
            @PathVariable Integer id) {
        return "删除成功";
    }

}

 

posted on 2017-12-07 17:37  Doublelin  阅读(4573)  评论(0编辑  收藏  举报