springboot集成swagger2

1.引入jar包 swagger3.0.0版本已经集成SpringBoot Starter 

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>

2.创建配置文件

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    // 访问 http://localhost:8083/swagger-ui/ 可以看到API文档
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                /*RequestHandlerselectors配置要扫描接口的方式
                  basePackage:指定要扫描的包,只有指定包下的接口会生成
                  .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                  any():扫描全部,所有的接口都会生成
                  none():不扫描
                  withClassAnnotation:扫描类上的注解,多数是一个注解的反射对象
                  withMethodAnnotation:扫描方法上的注解,用了注解的方法会生成
                  .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))*/
                .apis(RequestHandlerSelectors.any())
                //只生成符合下面配置的接口地址的接口
                //.paths(PathSelectors.ant("/admin/**"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 页面标题
                .title("慕慕生鲜")
                //描述
                .description("")
                //版本
                .version("")
                //作者信息
                .contact(new Contact("","",""))
                .build();
    }

}

3.swagger注解,用来描述接口信息

@Api: 用于类,标识这个类是swagger的资源
@ApiIgnore: 用于类,忽略该 Controller,指不对当前类做扫描
@ApiOperation: 用于方法,描述 Controller类中的 method接口
@ApiParam: 用于参数,单个参数描述,与 @ApiImplicitParam不同的是,他是写在参数左侧的。如( @ApiParam(name="username",value="用户名")Stringusername)
@ApiModel: 用于类,表示对类进行说明,用于参数用实体类接收
@ApiProperty:用于方法,字段,表示对model属性的说明或者数据操作更改
@ApiImplicitParam: 用于方法,表示单独的请求参数
@ApiImplicitParams: 用于方法,包含多个 @ApiImplicitParam
@ApiResponse: 用于方法,描述单个出参信息
@ApiResponses: 用于方法,包含多个@ApiResponse
@ApiError: 用于方法,接口错误所返回的信息

4.是否启动swagger,集成boot之后已经自带参数控制,可以分环境启动

springfox:
documentation:
enabled: true

 

5.如果访问首页404可以加下面代码试下,实现WebMvcConfigurer ,类名随意

@Configuration
public class SwaggerWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
    }
}

 

posted @ 2021-10-05 03:02  漩涡·海绵宝宝  阅读(91)  评论(0)    收藏  举报