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!