之前項目中整合Swagger都是直接通過依賴springfox-swagger、springfox-swagger-ui兩個jar包來實現(xiàn)的,最近發(fā)現(xiàn)springfox 3.0.0版本已經(jīng)有了自己的SpringBoot Starter,使用起來更契合SpringBoot項目,非常方便,推薦給大家!
使用官方Starter
我們先使用官方Starter來整合Swagger看看是否夠簡單!
- 首先在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();
}
}
- 訪問API文檔信息,訪問地址:http://localhost:8088/swagger-ui/image.png
- 兩步即可搞定SpringBoot集成Swagger,是不是很簡單!
與之前版本相比
之前我們使用的是springfox 2.9.2版本,接下來對比下3.0.0的SpringBoot Starter使用,看看有何不同!
- 舊版本需要依賴springfox-swagger2和springfox-swagger-ui兩個配置,新版本一個Starter就搞定了,而且之前的版本如果不使用新版本的swagger-models和swagger-annotations依賴,訪問接口會出現(xiàn)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>
新版本去除了一些第三方依賴,包括
guava,之前使用舊版本時就由于guava版本問題導致過依賴沖突新版本和舊版本文檔訪問路徑發(fā)生了變化,新版本為:http://localhost:8088/swagger-ui/ ,舊版本為:http://localhost:8088/swagger-ui.html
-
新版本中新增了一些SpringBoot配置,
springfox.documentation.enabled配置可以控制是否啟用Swagger文檔生成功能;image.png 比如說我們只想在dev環(huán)境下啟用Swagger文檔,而在prod環(huán)境下不想啟用,舊版本我們可以通過@Profile注解實現(xiàn);
@Configuration
@EnableSwagger2
@Profile(value = {"dev"})
public class Swagger2Config {
}
- 新版本我們在SpringBoot配置文件中進行配置即可,springfox.documentation.enabled在application-dev.yml配置為true,在application-prod.yml中配置為false。
整合Spring Security使用
我們經(jīng)常會在項目中使用Spring Security實現(xiàn)登錄認證,接下來我們來講下如何使用Swagger整合Spring Security,實現(xiàn)訪問需要登錄認證的接口。
- 如何訪問需要登錄認證的接口?只需在訪問接口時添加一個合法的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靜態(tài)資源的無授權訪問,比如首頁訪問路徑/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, // 允許對于網(wǎng)站靜態(tài)資源的無授權訪問
"/",
"/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;image.png
-
點擊Authorize按鈕后輸入Authorization請求頭,之后就可以訪問需要登錄認證的接口了。image.png
總結
Swagger官方Starter解決了之前整合Swagger的一系列問題,簡化了SpringBoot整合Swagger的過程,使用起來更加方便了。同時對于一些復雜的配置使用基本沒有變化,一些之前的使用方式依然可以使用!



