還在手動整合Swagger?Swagger官方Starter是真的香!

SpringBoot實戰電商項目mall(40k+star)地址:github.com/macrozheng/…css

摘要

以前項目中整合Swagger都是直接經過依賴springfox-swaggerspringfox-swagger-ui兩個jar包來實現的,最近發現springfox 3.0.0版本已經有了本身的SpringBoot Starter,使用起來更契合SpringBoot項目,很是方便,推薦給你們!html

使用官方Starter

咱們先使用官方Starter來整合Swagger看看是否夠簡單!java

  • 首先在pom.xml中添加springfox官方Swagger依賴;
<!--springfox swagger官方Starter-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
複製代碼
  • 添加Swagger的Java配置,配置好Api信息和須要生成接口文檔的類掃描路徑便可;
/** * Swagger2API文檔的配置 */
@Configuration
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SwaggerUI演示")
                .description("mall-tiny")
                .contact(new Contact("macro", null, null))
                .version("1.0")
                .build();
    }
}
複製代碼

  • 兩步便可搞定SpringBoot集成Swagger,是否是很簡單!

與以前版本相比

以前咱們使用的是springfox 2.9.2版本,接下來對比下3.0.0的SpringBoot Starter使用,看看有何不一樣!git

  • 舊版本須要依賴springfox-swagger2springfox-swagger-ui兩個配置,新版本一個Starter就搞定了,並且以前的版本若是不使用新版本的swagger-modelsswagger-annotations依賴,訪問接口會出現NumberFormatException問題;
<dependencies>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <exclusions>
            <exclusion>
                <groupId>io.swagger</groupId>
                <artifactId>swagger-annotations</artifactId>
            </exclusion>
            <exclusion>
                <groupId>io.swagger</groupId>
                <artifactId>swagger-models</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
    </dependency>
    <!--解決Swagger 2.9.2版本NumberFormatException-->
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-models</artifactId>
        <version>1.6.0</version>
    </dependency>
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>1.6.0</version>
    </dependency>
</dependencies>
複製代碼

  • 好比說咱們只想在dev環境下啓用Swagger文檔,而在prod環境下不想啓用,舊版本咱們能夠經過@Profile註解實現;
@Configuration
@EnableSwagger2
@Profile(value = {"dev"})
public class Swagger2Config {
    
}
複製代碼
  • 新版本咱們在SpringBoot配置文件中進行配置便可,springfox.documentation.enabledapplication-dev.yml配置爲true,在application-prod.yml中配置爲false。

整合Spring Security使用

咱們常常會在項目中使用Spring Security實現登陸認證,接下來咱們來說下如何使用Swagger整合Spring Security,實現訪問須要登陸認證的接口。跨域

  • 如何訪問須要登陸認證的接口?只需在訪問接口時添加一個合法的Authorization請求頭便可,下面是Swagger相關配置;
/** * Swagger2API文檔的配置 */
@Configuration
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))
                .paths(PathSelectors.any())
                .build()
                //添加登陸認證
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SwaggerUI演示")
                .description("mall-tiny")
                .contact(new Contact("macro", null, null))
                .version("1.0")
                .build();
    }

    private List<SecurityScheme> securitySchemes() {
        //設置請求頭信息
        List<SecurityScheme> result = new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
        result.add(apiKey);
        return result;
    }

    private List<SecurityContext> securityContexts() {
        //設置須要登陸認證的路徑
        List<SecurityContext> result = new ArrayList<>();
        result.add(getContextByPath("/brand/.*"));
        return result;
    }

    private SecurityContext getContextByPath(String pathRegex) {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(pathRegex))
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        List<SecurityReference> result = new ArrayList<>();
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        result.add(new SecurityReference("Authorization", authorizationScopes));
        return result;
    }
}
複製代碼
  • 咱們須要在Spring Security中配置好Swagger靜態資源的無受權訪問,好比首頁訪問路徑/swagger-ui/
/** * SpringSecurity的配置 * Created by macro on 2018/4/26. */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UmsAdminService adminService;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf()// 因爲使用的是JWT,咱們這裏不須要csrf
                .disable()
                .sessionManagement()// 基於token,因此不須要session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, // 容許對於網站靜態資源的無受權訪問
                        "/",
                        "/swagger-ui/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/swagger-resources/**",
                        "/v2/api-docs/**"
                )
                .permitAll()
                .antMatchers("/admin/login")// 對登陸註冊要容許匿名訪問
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)//跨域請求會先進行一次options請求
                .permitAll()
                .anyRequest()// 除上面外的全部請求所有須要鑑權認證
                .authenticated();
        // 省略若干配置......
    }
}
複製代碼
  • 調用登陸接口獲取token,帳號密碼爲admin:123456

  • 點擊Authorize按鈕後輸入Authorization請求頭,以後就能夠訪問須要登陸認證的接口了。

總結

Swagger官方Starter解決了以前整合Swagger的一系列問題,簡化了SpringBoot整合Swagger的過程,使用起來更加方便了。同時對於一些複雜的配置使用基本沒有變化,一些以前的使用方式依然可使用!restful

項目源碼地址

github.com/macrozheng/…markdown

本文 GitHub github.com/macrozheng/… 已經收錄,歡迎你們Star!

相關文章
相關標籤/搜索