1. 导入依赖
<!--swagger-->
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger-->
2. 编写swagger配置类
@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).select()
//扫描指定包中的swagger注解
//.apis(RequestHandlerSelectors.basePackage("cn.exrick.controller"))
//扫描所有有注解的api,用这种方式更灵活
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("ssm-single Api Documentation")
.description("ssm项目后台API接口文档")
.termsOfServiceUrl("https://www.baidu.com/")
.license("1043927441@qq.com")
.version("1.0.0")
.build();
}
}
3. 下载swagger ui资源
https://github.com/swagger-api/swagger-ui/tree/v2.1.5
只需要将dist文件夹复制到webapp目录下,然后重命名为swagger(名字可以随意,作访问路径用)
4. 配置springMVC.xml文件
<!-- 将 springSwaggerConfig加载到spring容器 -->
<!-- 将自定义的swagger配置类加载到spring容器 -->
<bean class="com.kingo.config.SwaggerConfig"/>
<!--不拦截swagger资源-->
<mvc:resources mapping="/swagger/**" location="/swagger/"/>
5.修改url地址
访问 http://localhost:8080/swagger/index.html 或着 http://localhost:8080/swagger-ui.html,有的可能是 http://localhost:8080/项目名/swagger/index.html,具体要看下图是否配置,我这里没有配置,所以就是访问http://localhost:8080/swagger/index.html
访问之后可能出现如下页面,并没有自己写的接口,这时需要修改url
改成 url = “/v2/api-docs”
再次访问,就出现自己写的接口
6. 全类型接口问题
上图可以看出,对于 /kingo/account/findAll 这个url,有多个请求方法,不符合我们的预期,查看Controller类
@Controller
@RequestMapping("/kingo/account")
@Api(value = "account的操作类", description = "用户类")
public class AccountController {
@Autowired
private IAccountService service;
@RequestMapping(value = "findAll")
// @RequestMapping(value = "findAll", method = {RequestMethod.GET})
@ResponseBody
@ApiOperation(value = "查询所有用户信息", notes = "查询用户", response = List.class)
public List<Account> findAll(){
return service.list();
}
@RequestMapping(value = "findById", method = {RequestMethod.GET})
@ResponseBody
@ApiOperation(value = "根据Id查询用户信息", notes = "查询特定用户", response = Account.class)
public Account findById(@RequestParam("id") String id){
return service.getById(id);
}
}
@RequestMapping(value = "findAll")
这个注解没有指定请求方法,改成
@RequestMapping(value = "findAll", method = {RequestMethod.GET})
重新部署项目访问,符合预期
另外,要想看到请求的结果,需要在接口加上@ResponseBody