- 引入jar
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
- 写配置文件
注意,配置类需要给Spring管理
@Configuration
@EnableWebMvc
@EnableSwagger2
@ComponentScan(basePackages = {"com.beyond.app.controller"})
public class Swagger2Config extends WebMvcConfigurationSupport {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())//调用下面apiInfo()方法
.select()
//Controller所在路径
.apis(RequestHandlerSelectors.basePackage("com.beyond.app.controller"))
.paths(PathSelectors.any())
.build();
}
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot结合swagger2构建Restful API")
.description("这是一个swagger2小型demo")
// http://localhost:8080/swagger-ui.html
.termsOfServiceUrl("http://localhost:8080")
.contact("bacyang")
.version("0.0.1")
.build();
}
}
- spring-mvc.xml配置
<!--加入 swagger2 资源文件-->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
<!--启动swagger2 -->
<bean class="com.beyond.app.Swagger2Config"/>
<!--静态资源处理,controller中找不到的,使用servlet 默认处理器处理-->
<mvc:default-servlet-handler/>
<!--如果配了拦截器, 不要拦截swagger2资源文件-->
<mvc:interceptors>
<mvc:interceptor>
<!--拦截请求-->
<mvc:mapping path="/**"/>
<!--不拦截swagger2资源文件-->
<mvc:exclude-mapping path="/swagger*/**"/>
<mvc:exclude-mapping path="/v2/**"/>
<mvc:exclude-mapping path="/webjars/**"/>
<bean class="com.beyond.app.inteceptor.TokenInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
-
编写接口文档
Swagger2 基本使用:@Api 描述类/接口的主要用途
@ApiOperation 描述方法用途
@ApiImplicitParam 描述方法的参数
@ApiImplicitParams 描述方法的参数(Multi-Params)
@ApiIgnore 忽略某类/方法/参数的文档
@Api("用户信息管理")
@RestController @RequestMapping("/user/*")
public class UserController {
private final static List<User> userList = new ArrayList<>(); { userList.add(new User("1", "admin", "123456"));
userList.add(new User("2", "jacks", "111111"));
}
@ApiOperation("获取列表")
@GetMapping("list") public List userList() { return userList; } @ApiOperation("新增用户") @PostMapping("save")
public boolean save(User user) {
return userList.add(user);
}
@ApiOperation("更新用户")
@ApiImplicitParam(name = "user", value = "单个用户信息", dataType = "User")
@PutMapping("update")
public boolean update(User user) {
return userList.remove(user) && userList.add(user);
}
@ApiOperation("批量删除")
@ApiImplicitParam(name = "users", value = "N个用户信息", dataType = "List<User>")
@DeleteMapping("delete")
public boolean delete(@RequestBody List<User> users) {
return userList.removeAll(users); }
}
- 访问
端口后面有系统名则需要加上
http://localhost:8080/swagger-ui.html
网友评论