1、引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
2、启动类加上注解
@EnableSwagger2
@SpringBootApplication
public class Swagger2Application {
public static void main(String[] args) {
SpringApplication.run(Swagger2Application.class, args);
}
}
3、创建swagger2的工具类
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;
/**
* Created with pengyouqi
* 2019/5/30 20:17
*/
@Configuration
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot-Swagger")
.description("闲置的小码农")
.version("1.0")
.build();
}
}
4、在controller上用注解解释各个方法的作用、参数的作用等等
@Api(value = "用户相关接口" ,tags="用户相关")
@RestController
public class UserController {
// 创建线程安全的Map
static Map<Integer, User> users = Collections.synchronizedMap(new HashMap<>());
/**
* 根据ID查询用户
* @param id
* @return
*/
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "path")
@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
public User getUserById (@PathVariable(value = "id") String id){
User r = new User();
try {
r.setId(id);
r.setName("88");
r.setAge("21");
r.setHeight("183");
r.setHeight("63");
} catch (Exception e) {
e.printStackTrace();
}
return r;
}
}
5、各个注解的作用
@ApiOperation注解用于放在方法上面,其中value是该类的简短的叙述,notes一般是该方法的详细描述。
@ApiImplicitParam注解用于表明前端传入的name参数的名字,
required是否为必需项,
dataType参数类型,
paramType传递方式(query表示使用url问号的方式传参,这种比较常用,如果使用formData的方式进行传参,那么paramType的值为 form).
当有多个参数时,需要用@ApiImplicitParams将@ApiImplicitParam包起来