技能get——springmvc4与Swagger2

配置Swagger2的用途

项目中,服务端开发人员通常要将接口定义文档,给客户端同学,QA同学,方便团队内部人员的合作。

原理及演变参考:https://blog.csdn.net/qq_25615395/article/details/70229139

如何配置swagger2

配置前注意事项:

  • spring版本与swagger的对应
  • 配置好后,自己遇到了不少问题,网上查资料可以解决(不过本人花了一天找各种报错原因,解决后,才通了呜呜呜)

1、pom.xml

<!-- ========swagger2 api自动生成工具 start======== -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.7.0</version>
			<exclusions>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-core</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-beans</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-context</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-context-support</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-aop</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-tx</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-orm</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-jdbc</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-web</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-webmvc</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-oxm</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.7.0</version>
		</dependency>
		<!-- ========swagger2 api自动生成工具 end======== -->

2、SwagerConfig配置

package com.swagger.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
* Swagger配置文件。
* [Springfox官方集成文档](http://springfox.github.io/springfox/docs/current/)
* [Swagger注解官方文档](https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X)
* <p>
* 配置注意事项:
* 1. swagger及swagger-ui的添加,注意版本
* 2. 该config文件的注解添加,@Configuration与@EnableSwagger2为必须添加
* 3. 配置servlet-mapping为"/",因为会生成静态文件,因此需要注意路径穿透
*
*
*/
@EnableWebMvc
@Configuration
@EnableSwagger2
@ComponentScan(basePackages = "com.tool.controller") //需要扫描的包路径
public class SwaggerConfig extends WebMvcConfigurationSupport {

    /**
    * 根据配置读取是否开启swagger文档,针对测试与生产环境采用不同的配置
    */
    @Value("${swagger.enable}")
    private boolean isSwaggerEnable;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("business-api")
                .enable(isSwaggerEnable)
                .apiInfo(apiInfo()).select()
                // 对所有该包下的Api进行监控,如果想要监控所有的话可以改成any()
                .apis(RequestHandlerSelectors.basePackage("com.tool.controller"))
                // 对所有路径进行扫描
                .paths(PathSelectors.any())
                .build();
    }

    /**
    * @return 生成文档说明信息
    */
    private ApiInfo apiInfo() {
        Contact contact = new Contact("xxx", "", "[email protected]");

        return new ApiInfoBuilder()
        		.contact(contact)
                .title("API文档")//                .title("xiaoAPI")   //子标题

                .description("接口文档")
                .termsOfServiceUrl("http://127.0.0.1:8078")
				.version("1.0.0").build();

	}
}

3、application-mvc配置

 mapping="/webjars/**"
    location="classpath:/META-INF/resources/webjars/" />
    <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
    
	<mvc:default-servlet-handler />

4、web.xml配置

<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/v2/api-docs</url-pattern>
	</servlet-mapping>
<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

5、controller配置

@Controller
@RequestMapping("/url")
@Api(tags = "ejfjjdjsjd", value = "/url") // swagger分类标题注解
public class MappingController {
	@Autowired
	private RequestMappingHandlerMapping requestMappingHandlerMapping;
	private static LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();

	@ApiOperation(value = "登录", httpMethod = "POST", notes = "用户登录文档说明", consumes = "application/Json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username", value = "用户名", required = true, defaultValue = "xiao", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "password", value = "密码", required = true, defaultValue = "xiao", paramType = "query", dataType = "String") })
	@RequestMapping(value = "login", method = RequestMethod.GET)
	@ResponseBody
	// 登录接口
	public Object login(String username, String password, HttpSession session, HttpServletResponse httpServletResponse,
			HttpServletRequest request) {

		return "dddd";
	}
}

6、配置效果

ip:端口号+项目/swagger-ui.html#

技能get——springmvc4与Swagger2