现阶段,JavaWeb开发,前后端分离已成主流。在开发阶段,前后端工程师约定好数据交互接口,实现并行开发和测试;在运行阶段前后端分离模式需要对web应用进行分离部署,前端使用http或者其他协议进行交互请求。因此,后台接口服务中,我们可以借助swagger来定义接口及其信息。
关于swagger的详细信息,大家可以其去官网浏览
Swagger官网:
我的感觉就是它是一种可视化的调试工具,哈哈哈。。。。。
接下来看看在springboot项目中如何整合Swagger。
1、配置pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2、创建swagger配置类
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2).
apiInfo(apiInfo()).
select().
apis(RequestHandlerSelectors.basePackage("com.example.examonlineweb.controller")).
paths(PathSelectors.any()).
build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder().
title("前后端分离项目中使用swagger2构建restful api").
description("第一次在springboot项目中集成swagger2").
contact("xxxxxx").
version("1.0").build();
}
}
3、这启动类中加上注解
@EnableSwagger2
4、注意:springboot项目整合swagger要注意两者的版本,springboot项目的版本低,相应的swagger版本不能太高,反之亦然,避免项目报错。
比如说:我之前亲身遇到的一个问题,springboot版本为2.2.1,swagger版本为2.2.2,项目启动就会报如下错误:
2019-12-08 16:17:00.058 INFO 8976 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-12-08 16:17:00.534 WARN 8976 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'linkDiscoverers' defined in class path resource [org/springframework/hateoas/config/HateoasConfiguration.class]: Unsatisfied dependency expressed through method 'linkDiscoverers' parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.plugin.core.PluginRegistry' available: expected single matching bean but found 15: modelBuilderPluginRegistry,modelPropertyBuilderPluginRegistry,typeNameProviderPluginRegistry,documentationPluginRegistry,apiListingBuilderPluginRegistry,operationBuilderPluginRegistry,parameterBuilderPluginRegistry,expandedParameterBuilderPluginRegistry,resourceGroupingStrategyRegistry,operationModelsProviderPluginRegistry,defaultsProviderPluginRegistry,pathDecoratorRegistry,relProviderPluginRegistry,linkDiscovererRegistry,entityLinksPluginRegistry
2019-12-08 16:17:00.535 INFO 8976 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2019-12-08 16:17:00.539 INFO 8976 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-12-08 16:17:00.549 INFO 8976 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
Disconnected from the target VM, address: '127.0.0.1:64025', transport: 'socket'
2019-12-08 16:17:00.554 ERROR 8976 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method linkDiscoverers in org.springframework.hateoas.config.HateoasConfiguration required a single bean, but 15 were found:
- modelBuilderPluginRegistry: defined in null
- modelPropertyBuilderPluginRegistry: defined in null
- typeNameProviderPluginRegistry: defined in null
- documentationPluginRegistry: defined in null
- apiListingBuilderPluginRegistry: defined in null
- operationBuilderPluginRegistry: defined in null
- parameterBuilderPluginRegistry: defined in null
- expandedParameterBuilderPluginRegistry: defined in null
- resourceGroupingStrategyRegistry: defined in null
- operationModelsProviderPluginRegistry: defined in null
- defaultsProviderPluginRegistry: defined in null
- pathDecoratorRegistry: defined in null
- relProviderPluginRegistry: defined by method 'relProviderPluginRegistry' in class path resource [org/springframework/hateoas/config/HateoasConfiguration.class]
- linkDiscovererRegistry: defined in null
- entityLinksPluginRegistry: defined by method 'entityLinksPluginRegistry' in class path resource [org/springframework/hateoas/config/WebMvcEntityLinksConfiguration.class]
Action:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
Process finished with exit code 1
于是乎,我将swagger的版本提升至2.9.2,项目启动OK。此处,请注意,避免入坑。
这样,整合swagger就完成了,接下来就可以写接口了。
5、实例
package com.example.springbootweb.controller;
import com.example.springbootweb.entity.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping("/users")
public class UserController {
static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long,User>());
@ApiOperation(value="获取用户列表",notes = "")
@RequestMapping(value={""},method = RequestMethod.GET)
public List<User> getUsers(){
List<User> u = new ArrayList<>(users.values());
return u;
}
@ApiOperation(value="创建用户",notes = "根据User对象创建用户")
@ApiImplicitParam(name="user",value="用户详细实体user",required = true,dataType = "User")
@RequestMapping(value="", method=RequestMethod.POST)
public String postUser(@RequestBody User user) {
users.put(user.getId(), user);
return "success";
}
@ApiOperation(value="获取用户详细信息",notes = "根据id获取")
@ApiImplicitParam(name="id",value="用户id",required = true,dataType = "Long",paramType = "path")
@RequestMapping(value="/{id}",method = RequestMethod.GET)
/*@ApiImplicitParam(name="id",value="用户id",required = true,dataType = "Long",paramType = "query")
@RequestMapping(value="/edit",method = RequestMethod.GET)*/
public User getById(@PathVariable Long id){
return users.get(id);
}
@ApiOperation(value="更新用户信息",notes = "根据id更新")
@ApiImplicitParams({
@ApiImplicitParam(name="id",value="用户id",required = true,dataType = "Long",paramType = "path"),
@ApiImplicitParam(name="user",value="用户详细实体User",required = true,dataType = "User")
})
@RequestMapping(value="/{id}",method = RequestMethod.PUT)
public String update(@PathVariable Long id,@RequestBody User user){
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id,u);
return "success";
}
@ApiOperation(value="删除用户",notes = "根据id删除用户")
@ApiImplicitParam(name="id",value="用户id",required = true,dataType = "Long",paramType = "path")
@RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
public String delete(@PathVariable Long id){
users.remove(id);
return "success";
}
}
http://localhost:8080/swagger-ui.html即可访问。