代码详情:https://download.csdn.net/download/sweet__queen/10970801
1.创建springboot项目,此次使用的是idea编译工具
至此项目创建完成,可以看下项目架构
2.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>
3.添加swaggerui配置类,创建配置swagger的相关文件
@Configuration
@EnableSwagger2
public class Swagger2Config {
//swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
@Bean
public Docket creatRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())//调用下面的APIInfo()方法
.select() //选择哪些路径和api会生成document
//包 所在路径
.apis(RequestHandlerSelectors.basePackage("com.example.springbootswagger"))
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))//对所有API进行监控
.paths(PathSelectors.any())//对所有路径进行监控
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
//页面标题
.title("springboot结合swagger2构建的Restful Api")
//描述
.description("这是一个swagger2小型demo")
//版本号
.version("1.0")
.build();
}
}
4.至此关于swagger基本配置已经完成,可以正常创建实体类和controller类
在实体类中
在controller中
@RestController
@RequestMapping("api")
@Api("api")
public class helloController {
// @Autowired
// private User user;
static Map<Long , User> map = new ConcurrentHashMap<>();
@RequestMapping(value = "/hello",method = RequestMethod.GET)
@ApiOperation(value = "打招呼")
public String index(){
return "hello world";
}
@RequestMapping(value = "lihd/{name}",method = RequestMethod.POST)
public String test(@ApiParam(name = "name", value = "用户名")@PathVariable String name){
return "lihd test fist content---"+name;
}
@ApiOperation(value = "获取用户列表")
@RequestMapping(value = "getuserlist",method = RequestMethod.GET)
public List<User> getList() {
List<User> list = new ArrayList<>(map.values());
return list;
}
}
5.点击运行,浏览器中输入http://localhost:8080/swagger-ui.html 即可进行访问
注解解释:
常用swaggerui注解:
- @Api()用于类;
表示标识这个类是swagger的资源
- @ApiOperation()用于方法;
表示一个http请求的操作
- @ApiParam()用于方法,参数,字段说明;
表示对参数的添加元数据(说明或是否必填等)
- @ApiModel()用于类
表示对类进行说明,用于参数用实体类接收
- @ApiModelProperty()用于方法,字段
表示对model属性的说明或者数据操作更改
- @ApiIgnore()用于类,方法,方法参数
表示这个方法或者类被忽略
- @ApiImplicitParam() 用于方法
表示单独的请求参数
- @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam