1、导入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
2、编写swagger2的配置类
@Configuration
public class SwaggerConfig {
private static final String TOKEN = "";
@Bean
public Docket api() {
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
tokenPar.name("Authorization")
.description("令牌")
.defaultValue(TOKEN)
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build();
pars.add(tokenPar.build());
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars)
.apiInfo(apiInfo());
return docket;
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("swagger2 ----")
.version("1.0")
.description("API 描述")
.build();
}
}
3、启动类上加上@EnableSwagger2注解
@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4、在接口中使用swagger注解
@RestController
@RequestMapping("/user")
@Api(value = "用户中心接口", description = "用户中心api")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getUser/{phone}")
@ApiOperation(value = "通过手机号查询用户",httpMethod = "GET",produces = MediaType.APPLICATION_JSON_VALUE,response = User.class)
public User getUser(@ApiParam(name = "手机号", required = true) @PathVariable("phone") String phone){
return userService.findByphone(phone);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/78e723f51a0d3f698a32a29e431471ee.png#pic_center)