SpringBoot實戰電商項目mall(40k+star)地址:github.com/macrozheng/…css
以前項目中整合Swagger都是直接經過依賴springfox-swagger
、springfox-swagger-ui
兩個jar包來實現的,最近發現springfox 3.0.0版本已經有了本身的SpringBoot Starter,使用起來更契合SpringBoot項目,很是方便,推薦給你們!html
咱們先使用官方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>
複製代碼
/** * 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();
}
}
複製代碼
以前咱們使用的是springfox 2.9.2版本,接下來對比下3.0.0的SpringBoot Starter使用,看看有何不一樣!git
springfox-swagger2
和springfox-swagger-ui
兩個配置,新版本一個Starter就搞定了,並且以前的版本若是不使用新版本的swagger-models
和swagger-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>
複製代碼
新版本去除了一些第三方依賴,包括guava
,以前使用舊版本時就因爲guava
版本問題致使過依賴衝突,具體能夠看下《給Swagger升級了新版本,沒想到竟然有這麼多坑!》;github
新版本和舊版本文檔訪問路徑發生了變化,新版本爲:http://localhost:8088/swagger-ui/ ,舊版本爲:http://localhost:8088/swagger-ui.htmlspring
新版本中新增了一些SpringBoot配置,springfox.documentation.enabled
配置能夠控制是否啓用Swagger文檔生成功能;api
dev
環境下啓用Swagger文檔,而在prod
環境下不想啓用,舊版本咱們能夠經過@Profile
註解實現;@Configuration
@EnableSwagger2
@Profile(value = {"dev"})
public class Swagger2Config {
}
複製代碼
springfox.documentation.enabled
在application-dev.yml
配置爲true,在application-prod.yml
中配置爲false。咱們常常會在項目中使用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;
}
}
複製代碼
/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();
// 省略若干配置......
}
}
複製代碼
admin:123456
;Authorize
按鈕後輸入Authorization
請求頭,以後就能夠訪問須要登陸認證的接口了。Swagger官方Starter解決了以前整合Swagger的一系列問題,簡化了SpringBoot整合Swagger的過程,使用起來更加方便了。同時對於一些複雜的配置使用基本沒有變化,一些以前的使用方式依然可使用!restful
github.com/macrozheng/…markdown
本文 GitHub github.com/macrozheng/… 已經收錄,歡迎你們Star!