Spring Boot 快速集成Swagger2

简介

Swagger2 是用于描述和生成 RESTful API 文档的项目工具,对于查阅和维护 API 文档都很便利。

springfox-swagger2 + springfox-swagger-ui

引入依赖

springfox-swagger2引入Swagger2,springfox-swagger-ui用于Swagger UI。

<dependencies>
  <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
  </dependency>
  <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
  </dependency>
</dependencies>

Swagger 配置

注解@EnableSwagger2,用于声明启用 Swagger2;
创建一个Docket实例用于配置 Swagger2;
apis()paths()方法用于过滤控制器Controller和方法Method

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(Predicates.or(RequestHandlerSelectors.basePackage("com.lrkj.admin.controller"),
                        RequestHandlerSelectors.basePackage("com.lrkj.app.controller")))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("TITLE")
                .description("DESC")
                .contact(new Contact("name", "url", "email"))
                .version("version 2.0")
                .build();
    }
}

WebMvc 配置

配置 Swagger2 相关静态资源的访问。

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

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

Spring Security 配置

主要配置放行 Swagger2 页面相关的路径。

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private AdminUserDetailService adminUserDetailService;
    @Resource
    private MD5PasswordEncoder passwordEncoder;
    @Bean
    public AdminAuthenticationFilter adminAuthenticationFilter() {
        return new AdminAuthenticationFilter();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(adminUserDetailService).passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()
                .loginPage("/auth/require")
                .and()
                .authorizeRequests()
                .antMatchers("/auth/require").permitAll()
                .antMatchers("/login", "/admin/index.html").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(adminAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
        ;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(ignoringAntPatterns());
    }
    
    private String[] ignoringAntPatterns() {
        return new String[] {
                "/doc.html",
                "/swagger-ui.html",
                "favicon.ico",
                "/webjars/**",
                "/swagger-resources/**",
                "/v2/api-docs/**"
        };
    }
}

浏览器访问

http://localhost:8080/swagger-ui.html

springfox-swagger2 + knife4j-spring-ui

引入依赖

knife4j-spring-ui是增强的 Swagger UI,提供文档说明和在线调试。

<dependencies>
  <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
  </dependency>
  <dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-ui</artifactId>
  </dependency>
</dependencies>

Swagger 配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(Predicates.or(RequestHandlerSelectors.basePackage("com.lrkj.admin.controller"),
                        RequestHandlerSelectors.basePackage("com.lrkj.app.controller")))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("TITLE")
                .description("DESC")
                .contact(new Contact("name", "url", "email"))
                .version("version 2.0")
                .build();
    }
}

WebMvc 配置

springfox-swagger-ui中配置的是/swagger-ui.html
knife4j-spring-ui中则配置的是/doc.html

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("file:/Users/wei/IdeaProjects/resources/");
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

Spring Security 配置

springfox-swagger-ui中对 Spring Security 的配置无异。

浏览器访问

http://localhost:8080/doc.html

Swagger 常用注解

  • @Api,标识类作为 Swagger 资源,用于类的说明,用在 Controller 类上
    • tags,类的说明标签
    • value,类的说明描述,无需关注和配置
  • @ApiOperation,标识为操作或HTTP方法,用于方法的说明,用在 Controller 方法上;
    • value,方法描述
    • notes,方法备注
    • tags,用于方法分组
  • @ApiParam,用于方法参数的说明,用在 Controller 方法参数中;
    • name,参数名
    • value,参数说明
    • required,是否必需
  • @ApiModel,表示响应数据的信息,用在响应类上;
    • value,模型别名,可用于表示数据类型,通常不设置
    • description,详细说明
  • @ApiModelProperty,表示响应数据的信息,用在响应类属性上。
    • name,参数名
    • value,参数说明
    • required,是否必需

参考

[1] Package io.swagger.annotations


推荐文章

AI最佳实践全栈式从0到1开发个人博客系统

  • 23
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我喺小VIE

努力创作,值得肯定●゜ⅴ゜)ノ

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值