增加Swagger配置
增加Swagger配置
在增加Swagger配置之前,我们要知道为什么要增加Swagger。
首先在开发中我们遇到的痛点:
在前后端开发的过程中,我们或多或少的被接口文档折磨过。
前端经常抱怨后端给的接口文档与实际的接口文档不一致
后端觉得编写文档以及对应的维护接口文档,会耗费大量的精力,经常来不及更新。
这次引入的Swagger就是为了解决这个问题。
目录
1.引入Swagger的jar包
<!--******************************swagger2部分********************************-->
<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
配置的地方需要修改两个部分
2.1.新增Swagger配置类
package edu.wan.swagger;
import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(true) // 是否禁用swagger
.useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger API文档")
.description("Swagger测试文档")
.version("1.0")
.build();
}
}
2.2.在配置文件(xml)中进行Swagger的配置
<!--swagger -->
<context:component-scan base-package="edu.wan.swagger"/>
<!--在没有配置这个Bean的时候,我的Swagger的访问一只存在问题,增加上这个就好了(有哪位大佬知道帮忙解释下感谢) -->
<bean class="springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration" id="swagger2Config" />
<!--对Swagger的静态路径进行特殊处理,要不然容易被SpringMVC进行拦截处理 -->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />
3.在Conteroller进行配置
/**
跨域请求的详解
场景1:假设该服务部署的8080端口,我需要调用8081的服务的方法,如果我直接调用的话
http://127.0.0.1:8080 -> http://127.0.0.1:8081 以为只要是
请求的协议(http或者https)、ip、端口 任意一个改变都属于跨域的请求
这是由Netscape 公司提出的安全策略
如果我把调用的8081提供服务的方法或者controlle配置上@CrossOrigin就可以进行跨域的调用了
*/
@CrossOrigin //解决请求跨域的问题
@RestController
@Controller
@RequestMapping("/user")
@Api(value = "UserController管理" ,tags = "UserController管理接口API")
public class UserController {
@GetMapping("/query")
@ApiOperation(value = "通过id查询对象接口",notes = "通过id查询对象接口", httpMethod = "post")
@ApiResponse(response = User.class, code = 200, message = "接口返回的数据")
public @ResponseBody User findUserById(){
int id = 1;
return userService.findById(id);
}
详细的为什么这么配置,请参考官网。
4.进行验证
启动服务
访问地址:ip+port/项目名/swagger-ui.html