还在手动整合Swagger?Swagger官方Starter是真的香!
之前项目中整合时髦的都是直接通过依赖斯普林福克斯-斯瓦格、斯普林福克斯-斯瓦格用户界面两个冲突包来实现的,最近发现springfox 3.0.0版本已经有了自己的启动程序,使用起来更契合回弹项目,非常方便,推荐给大家!
使用官方Starter
我们先使用官方起动机来整合时髦的看看是否够简单!首先在pom.xml中添加斯普林福克斯官方时髦的依赖;-斯普林福克斯斯瓦格官方启动器-
属国
groupIdio.springfox/groupId
artifactIdspringfox-boot-starter/artifactId
版本3 .0 .0/版本
/依赖性添加时髦的的Java 语言(一种计算机语言,尤用于创建网站)语言(一种计算机语言,尤用于创建网站)配置,配置好美国石油学会(美国石油协会)信息和需要生成接口文档的类扫描路径即可;/**
* Swagger2API文档的配置
*/
@配置
公共类Swagger2Config {
@豆
public Docket create restapi(){ 0
返回新的文件类型.SWAGGER _ 2)。apiInfo(apiInfo())。选择()。API(RequestHandlerSelectors。BasePackage(' com。宏。商场。很小。控制器’)。路径(路径选择器。any())。build();
}
私有ApiInfo ApiInfo(){ 0
返回新的ApiInfoBuilder()。标题(' SwaggerUI演示)。描述('小商场)。联系人(新联系人('宏,空,空))。版本(' 1.0 ')。build();
}
}访问应用程序接口文档信息,访问地址:http://localhost :8088/swag-ui/
两步即可搞定回弹集成霸气,是不是很简单!
与之前版本相比
之前我们使用的是springfox 2.9.2版本,接下来对比下3.0.0的回弹启动器使用,看看有何不同!旧版本需要依赖springfox-swagger2和斯普林福克斯-斯瓦格用户界面两个配置,新版本一个起动机就搞定了,而且之前的版本如果不使用新版本的霸气模特和斯瓦格-注释依赖,访问接口会出现NumberFormatException问题;属国
属国
groupIdio.springfox/groupId
artifactIdspringfox-swag 2/artifactId
不包括的项目:如接受服务项目是由投保以前已患有的疾病或伤害引致的
排除
groupIdio.swagger/groupId
artifactIdswagger-注释/artifactId
/排除
排除
groupIdio.swagger/groupId
artifactIdswagger模型
s</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版本问题导致过依赖冲突;新版本和旧版本文档访问路径发生了变化,新版本为:http://localhost:8088/swagger-ui/ ,旧版本为:http://localhost:8088/swagger-ui.html新版本中新增了一些SpringBoot配置,springfox.documentation.enabled配置可以控制是否启用Swagger文档生成功能;比如说我们只想在dev环境下启用Swagger文档,而在prod环境下不想启用,旧版本我们可以通过@Profile注解实现;@Configuration @EnableSwagger2 @Profile(value = {"dev"}) //旧版本 public class Swagger2Config { }新版本我们在SpringBoot配置文件中进行配置即可,springfox.documentation.enabled在application-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的配置 * */ @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的过程,使用起来更加方便了。同时对于一些复杂的配置使用基本没有变化,一些之前的使用方式依然可以使用!