前言:本次测试使用的版本是2.9.2
一,引入依赖
<!--swagger-ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
二,swagger配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Value("${jwt.header}")
private String tokenHeader;
@Value("${swagger.enabled}")
private Boolean enabled;
@Bean
public Docket createRestApi() {
ParameterBuilder parameterBuilder = new ParameterBuilder();
List<Parameter> params = new ArrayList<>();
parameterBuilder.name(tokenHeader).description("token")
.modelRef(new ModelRef("string"))
.parameterType("header")
.defaultValue("")
.required(true)
.build();
params.add(parameterBuilder.build());
return new Docket(DocumentationType.SWAGGER_2)
.enable(enabled)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build()
.globalOperationParameters(params);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("xxx 接口文档")
.version("2.9.2")
.contact(new Contact("项目地址","http://localhost:8090/","123456@qq.com"))
.build();
}
}
三,在WebConfig中配置web以便能直接访问swagger-ui.html
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("POST", "DELETE", "PUT", "GET");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0); // 配置web访问swagger-ui.html
}
}
四,项目整合Spring-Security的则需要放行swagger-ui.html
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// 禁用CSRF, 解决POST请求下的CSRF问题
.csrf().disable()
// 授权异常
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and()
// 不创建会话
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 过滤请求
.authorizeRequests()
.antMatchers(
HttpMethod.GET,
"/*.html",
"/**/*.css",
"/**/*.js"
).anonymous()
// swagger-ui
.antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/*/api-docs").permitAll()
// 文件
.antMatchers("/attach/**").permitAll()
// 放行OPTIONS请求
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// 自定义匿名访问所有url放行 : 允许匿名和带权限以及登录用户访问
.antMatchers(anonymousUrlSet.toArray(new String[0])).permitAll()
// 所有请求都需要认证
.anyRequest().authenticated()
// 防止iframe 造成跨域
.and().headers().frameOptions().disable();
httpSecurity
.addFilterBefore(jwtAuthorizationTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
五,接下来就是使用swagger注解了,具体注解自行百度
@RestController
@Api(tags = "系统管理: 用户管理")
public class UserController {
}
完