pom.xml 导入jar
配置spring-mvc.xml文件
<mvc:resources mapping="docs.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
<mvc:default-servlet-handler/>
docs.html: 是映射swagger-ui-layer文件jar里面的/META-INF/resources/这个目录下docs.html
swagger-ui.html:是映射swagger-ui文件jar里面的/META-INF/resources/这个目录下docs.html
/webjars/**:映射到swagger-ui文件里面这个/META-INF/resources/webjars/目录下
注意点:这里用到spring mvc默认的servlet,这个是专门来处理静态资源的,在spring-mvc配置文件里面增加
mvc:default-servlet-handler,或者在web.xml文件里面配置也行,配置如下:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
新建SwaggerConfig配置java类文件
@Configuration
@EnableSwagger2
@EnableWebMvc
@ComponentScan(basePackages = {包路径})
public class SwaggerConfig {
@Bean
public Docket customDocket() throws IOException, UNAuthorizedCallerException {
//这里判断是线上还是线下,这里我用的是枚举,需要自己写两个值 ONLINE(0),OFFLINE(1),增加 valueOf方法
if(SwaggerEnvEnum.valueOf(edufeSetting.getEnableSwagger()) == SwaggerEnvEnum.ONLINE) {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfoOnline())
.select()
.paths(PathSelectors.none())
.build();
}else {
return new Docket(DocumentationType.SWAGGER_2)
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(false)
.pathMapping("/")
.select()
.build()
.apiInfo(apiInfo());
}
}
/**
* 开发和测试环境使用
* @return
*/
private ApiInfo apiInfo() {
Contact contact = new Contact("XX测试接口", "/");
return new ApiInfoBuilder()
.contact(contact)
.title("XX接口")
.description("接口描述")
.version("1.0.0")
.build();
}
/**
* 预生成环境使用
* @return
*/
private ApiInfo apiInfoOnline() {
return new ApiInfoBuilder()
.title("")
.description("")
.license("")
.licenseUrl("")
.termsOfServiceUrl("")
.version("")
.contact(new Contact("","", ""))
.build();
}
}
swagger常用的注解配置
常用注解:
@Api()用于类; 表示标识这个类是swagger的资源
@ApiOperation()用于方法; 表示一个http请求的操作
@ApiParam()用于方法,参数,字段说明; 表示对参数的添加元数据(说明或是否必填等)
@ApiModel()用于类 表示对类进行说明,用于参数用实体类接收
@ApiModelProperty()用于方法,字段 表示对model属性的说明或者数据操作更改
@ApiIgnore()用于类,方法,方法参数 表示这个方法或者类被忽略
@ApiImplicitParam()用于方法 表示单独的请求参数
@ApiImplicitParams()用于方法,包含多个 @ApiImplicitParam
具体使用举例说明:@Api()用于类;表示标识这个类是swagger的资源 tags–表示说明 value–也是说明,可以使用tags替代但是tags如果有多个值,会生成多个list
@ApiOperation()用于方法;表示一个http请求的操作 value用于方法描述 notes用于提示内容 tags可以重新分组(视情况而用)@ApiParam()用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等) name–参数名 value–参数说明 required–是否必填
@ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收 value–表示对象名 description–描述 都可省略
@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改 value–字段说明 name–重写属性名字 dataType–重写属性类型 required–是否必填 example–举例说明 hidden–隐藏
@ApiIgnore()用于类或者方法上,可以不被swagger显示在页面上 比较简单, 这里不做举例
@ApiImplicitParam()用于方法
表示单独的请求参数
@ApiImplicitParams()用于方法,包含多个 @ApiImplicitParam
name–参数ming
value–参数说明
dataType–数据类型
paramType–参数类型
example–举例说明
参考博客:/u014231523/article/details/76522486