swagger ui是一个API在线文档生成和测试的利器,在某种程度上可以媲美常用的postman,网上有很多它的整合教程,但是没有考虑到安全问题,下面是它的整合流程。
1、maven依赖:
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
2、启动主类添加注解
@EnableWebMvc
3、创建Swagger2类放在与启动主类同一目录下
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.google.common.base.Predicates;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
*
* @Title: Swagger设置类
* @Package com.lovnx.charge
* @author yezhiyuan
* @date 2017年5月10日 上午9:45:55
* @version V1.0
*/
@Configuration
@ComponentScan(basePackages = { "com.lovnx.*.controller.*" })//配置controller路径
@EnableSwagger2
@SuppressWarnings({"unchecked","deprecation"})
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.paths(Predicates.or(
//这里添加你需要展示的接口
PathSelectors.ant("/account/**"),
PathSelectors.ant("/xxx/**"),
PathSelectors.ant("/qqq/**"),
PathSelectors.ant("/eee/**")
)
)
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API平台名字")
.description("说明RESTful APIs")
.contact("xxx@qq.com")
.version("1.0")
.build();
}
}
4、Swagger配置路径重定向(不加这个类会报错)
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
*
* @Title: Swagger配置路径重定向
* @Package com.config
* @author yezhiyuan
* @date 2017年5月10日 上午9:45:16
* @version V1.0
*/
@Configuration
public class SwaggerWebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
5、controller添加注解
类上添加:@Api(description="这个controller是干嘛的")
方法上添加:@ApiOperation(value="这个方法是干嘛的", notes="详细注释")
6、配置完成,访问API页面
http://localhost:服务端口/swagger-ui.html
7、整合Spring Security实现访问API页面输入用户名密码
maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置文件添加:
security.basic.path=/swagger-ui.html
security.basic.enabled=true
security.user.name=lovnx
security.user.password=123456