2018-08-27再次验证该文无误。。。
一、前言
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.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
三、创建配置类
Swagger需要一个配置类来进行对swagger的基本配置,该配置类的类名可以随便写,比如Swagger2Config,这个类只需要两个注解,不需要@ComponentScan("com.wqc.controller")了。。。2018-08-27
配置类:
@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.wqcdemo.com")
.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,写了@Api后显示反而不好...
@Api(tags="你好,世界")
@RestController
public class HelloController {
@ApiOperation("哈罗")
@RequestMapping(value="/hello",method=RequestMethod.GET)
public String index() {
return "Hello World";
}
}
六、测试
启动application 并访问http://localhost:8080/swagger-ui.html