1.首先需要导入jar包
<!-- 生成swagger接口 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.5.0</version> </dependency> <!--web展示生成的接口 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.5.0</version> </dependency> <!-- 好像是生成接口中用到的序列化,maven依赖中已经存在,但不知道为啥还是需要这里显示导入 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.2</version> </dependency>
2.新建配置文件 Swagger2Configuration
@EnableSwagger2
@Configuration
@EnableWebMvc
public class Swagger2Configuration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())//api信息
.select()
.apis(RequestHandlerSelectors.any()) //api选择
.paths(PathSelectors.any())//指定api路径
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(" 接口列表 v1.0.0")
.description("swagger_test")
.version("1.0.0")
.build();
}
}
3.修改XML配置文件
<!-- 使静态资源使用默认的Servlet 来处理,不声明的话,可能访问不到 swagger-ui.html--> <mvc:default-servlet-handler /> <!-- 这里不显示声明bean,会出现页面能访问到接口不能展示的情况 --> <bean class="com.demo.swagger.config.Swagger2Configuration"/>
4.编写swagger风格的接口
@Api(value="swaggertest")
@Controller
public class SwaggerTestAction {
@ApiOperation("swagger_test")
@ResponseBody
@RequestMapping(value = "/test2/{id}",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
public String test (@ApiParam @PathVariable("id")String id){
return id;
}
}