1、引入pom
<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>
2、添加Swagger配置类
import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* IT之美 Swagger配置类
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(true)
.useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger API文档")
.description("接口文档")
.version("1.0")
.build();
}
}
3、添加Controller
import com.itzhimei.handle.Person7;
import com.itzhimei.handle.Person8;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
/**
* Hello world!
*
*/
@Api(tags = "Hello World App2")
@RestController
public class App2
{
@Autowired
private Person7 person7;
@Autowired
private Person8 person8;
@GetMapping("/hello2")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello2 %s!", name);
}
@GetMapping("/getPerson7")
public Person7 getPerson7() {
return person7;
}
@GetMapping("/getPerson8")
public Person8 getPerson8() {
return person8;
}
}
4、启动应用程序
5、查看文档
localhost:8081/swagger-ui.html#/
页面输出:
==========================
测试接口文档
Hello World App2
App 2
Hello World App3
App 3
==========================