Swagger介绍及集成
1、新建⼀个SpringBoot Web项⽬2、导⼊相关依赖
3、编写⼀个Hello⼯程4、配置Swagger(空的)
@Configuration//表明是⼀个配置类@EnableSwagger2 //开启swagger2public class SwaggerConfig {}
5、配置Swagger,在配置类⾥⾯
①Swagger的Bean实例Docket,配置显⽰信息
@Bean
public Docket docket(Environment environment){
//题⽬:在⽣产环境中不使⽤swagger,测试环境中使⽤swagger //配置Swagger的Docket的Bean实例
return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select()
//RequestHandlerSelectors:配置要扫描接⼝的⽅式 //basePackage:指定要扫描的包 //any:扫描全部 //none:不扫描
//withClassAnnotation:扫描类上的注解,需要的参数是⼀个注解的反射对象 .apis(RequestHandlerSelectors.basePackage(\"com.joy.swagger.controller\")) //过滤什么路径
//.paths(PathSelectors.ant(\"/joy/**\")) .build() ; }
private ApiInfo apiInfo(){
Contact contact = new Contact(\"joy\ return new ApiInfo( \"joy\
\"Api Doc\ \"urn:tos\
\"http://www.baidu.com\ contact,
\"Apache 2.0\
\"http://baidu.com\ new ArrayList() ); }
②配置扫描接⼝及开关编写controller层
@RestController
public class HelloController { @GetMapping(value=\"/hello\") public String hello(){ return \"hello\"; }}
配置Docket
@Bean
public Docket docket(Environment environment){ //设置要显⽰的Swagger环境
Profiles profiles = Profiles.of(\"dev\
//题⽬:在⽣产环境中不使⽤swagger,测试环境中使⽤swagger //配置Swagger的Docket的Bean实例
//获取项⽬的环境:通过environment.acceptsProfiles判断是否处在⾃⼰设置的环境当中 boolean flag = environment.acceptsProfiles(profiles); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo())
//设置Swagger是否启动,false:不启动,true:启动,此时实现了动态监听 .enable(flag) .select()
//RequestHandlerSelectors:配置要扫描接⼝的⽅式 //basePackage:指定要扫描的包 //any:扫描全部 //none:不扫描
//withClassAnnotation:扫描类上的注解,需要的参数是⼀个注解的反射对象 .apis(RequestHandlerSelectors.basePackage(\"com.joy.swagger.controller\")) //过滤什么路径
//.paths(PathSelectors.ant(\"/joy/**\")) .build() ; }
分组的实现和接⼝注解及⼩结
①分组:多加⼏个Docket
@Bean
public Docket docket1(Environment environment){
return new Docket(DocumentationType.SWAGGER_2).groupName(\"A\"); }
@Bean
public Docket docket2(Environment environment){
return new Docket(DocumentationType.SWAGGER_2).groupName(\"B\"); }
@Bean
public Docket docket3(Environment environment){
return new Docket(DocumentationType.SWAGGER_2).groupName(\"C\"); }
③编写实体类:User
public class User {
private String username; private String password; }
④为了使实体类在mould中显⽰,在Controller中返回
@RestController
public class HelloController { @GetMapping(value=\"/hello\") public String hello(){ return \"hello\"; }
//只要我们的接⼝中,返回值存在实体类,他就会被扫描到swagger中 @PostMapping(value = \"/user\") public User user(){ return new User(); }}
⑤可以在实体类中加注解,解释变量、⽅法、类,显⽰在页⾯上就会有解释
@ApiModel(\"⽤户实体类\")public class User {
@ApiModelProperty(\"⽤户\") private String username; @ApiModelProperty(\"密码\") private String password;}
⑥也可以在控制类中加接⼝注解,解释接⼝
@ApiOperation(\"⽤户\")
@PostMapping(value = \"/user\") public User user(){ return new User(); }
因篇幅问题不能全部显示,请点此查看更多更全内容