实体注解
效果图:
- Controller注解
这里给参数添加注解,我倾向于使用下面这种
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "跳转到的页数", dataType = "Integer", required = true, paramType = "query"),
@ApiImplicitParam(name = "size", value = "每页展示的记录数", dataType = "Integer", required = true, paramType = "query")
})
public ZingResult selectAllUsers(Integer page, Integer size) {
return ZingResult.success();
}
而不是这种
public ZingResult selectOne(@ApiParam(name="page",value="页码",required=true) Integer page,@ApiParam(name="size",value="页面数量",required=true) Integer size) {
return ZingResult.success();
}
因为,第一种是方法上添加注解,而不是像第二种的在原有方法参数列表中添加注解的方式。
效果图
3 Swagger文档配置类
3.1配置文件
Swagger开关
SWAGGER.ENABLE = true
#Swagger API配置
SWAGGER.TITLE = 基础平台 RESTful APIs
SWAGGER.DESC = 基础平台 RESTful 风格的接口文档,内容详细,极大的减少了前后端的沟通成本,同时确保代码与文档保持高度一致,极大的减少维护文档的时间。
3.2 配置类
配置类需要注入到IOC容器中
<!--配置swaggerui-->
<bean id="swagger2Config" class="com.zing.swagger.Swagger2Config"/>
/**
* 配置swagger信息
*
* @author 于云秀
*/
//启用Swagger2
@EnableSwagger2
public class Swagger2Config extends WebMvcConfigurationSupport {
@Value("${SWAGGER.ENABLE}")
private boolean swaggerEnable;
@Value("${SWAGGER.TITLE}")
private String swaggerTitle;
@Value("${SWAGGER.DESC}")
private String swaggerDesc;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).select()
//扫描指定包中的swagger注解
.apis(RequestHandlerSelectors.basePackage("com.zing.controller"))
//扫描所有有注解的api,用这种方式更灵活
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
@Bean
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//标题
.title(swaggerTitle)
//描述
.description(swaggerDesc)
//服务条款
.termsOfServiceUrl("http://www.tfjybj.com")
//版本号
.version("1.0.0")
//许可证
.license("LICENSE")
//许可证地址
.licenseUrl("http://www.dmsdbj.com")
.build();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (swaggerEnable) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
}
3.3 注意事项
属性文件中存在中文,则需要在加载属性文件的时候指定编码格式,根据需要选择以下3种
• 使用PropertyPlaceholderConfigurer加载
<!-- 加载配置文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:dubbo-server.properties</value>
<value>classpath:server.properties</value>
</list>
</property>
<property name="fileEncoding" value="utf-8" />
</bean>
• 使用context:property-placeholder 加载
• 使用注解加载
@PropertySource(value = "classpath:conf/copyWriteUI.properties",encoding = "utf-8")
3.4 最终效果