天天看点

spring整合swagger的案例

1.swagger在线api文档生成工具:

相关依赖:在使用swagger时除了swagger本身的依赖外,还需要第三方json依赖的支持

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.spring.swagger</groupId>
  <artifactId>spring_swagger</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>spring_swagger Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <!-- 
   
   spring 相关依赖
   
    -->
    <!-- 持久层依赖 -->
    <dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-orm</artifactId>
		    <version>5.2.9.RELEASE</version>
		</dependency>
		<!-- spring的基础依赖 -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-context</artifactId>
		    <version>5.2.9.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-beans</artifactId>
		    <version>5.2.9.RELEASE</version>
		</dependency>
		
		<!-- 数据库连接驱动包 -->
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>5.1.38</version>
		</dependency>
		
		<!-- AOP-->
		<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
		<dependency>
		    <groupId>org.aspectj</groupId>
		    <artifactId>aspectjweaver</artifactId>
		    <version>1.9.5</version>
		    <scope>runtime</scope>
		</dependency>
		  <!-- https://mvnrepository.com/artifact/javax.annotation/jsr250-api -->
		<dependency>
		    <groupId>javax.annotation</groupId>
		    <artifactId>jsr250-api</artifactId>
		    <version>1.0</version>
		</dependency>
		  
		  <!-- MyBaties相关依赖 -->
		  <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.5.3</version>
		</dependency>
		  <!-- spring整合MyBaties相关依赖 -->
		  <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>1.3.2</version>
		</dependency>
		
		<!-- 数据连接池-->
		<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>druid</artifactId>
		    <version>1.1.21</version>
		</dependency>
		
		  
   <!-- 
   
   springmvc 相关依赖
   
    -->
    	<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-webmvc</artifactId>
	    <version>5.2.9.RELEASE</version>
	</dependency>

	  <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-web</artifactId>
	    <version>5.2.9.RELEASE</version>
	</dependency>
	  <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>javax.servlet-api</artifactId>
	    <version>3.1.0</version>
	    <scope>provided</scope>
	</dependency>
	
	<!-- jstl支持依赖 -->
	<dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.servlet.jsp</groupId>
                    <artifactId>jsp-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jstl-impl</artifactId>
            <version>1.2</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.servlet.jsp</groupId>
                    <artifactId>jsp-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.servlet.jsp.jstl</groupId>
                    <artifactId>jstl-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        
	 <!-- https://mvnrepository.com/artifact/junit/junit -->
	<dependency>
	    <groupId>junit</groupId>
	    <artifactId>junit</artifactId>
	    <version>4.12</version>
	    <scope>test</scope>
	</dependency>
	
	<!--json依赖  -->
	<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-databind</artifactId>
	    <version>2.12.0</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-core</artifactId>
	    <version>2.12.0</version>
	</dependency>
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-annotations</artifactId>
	    <version>2.12.0</version>
	</dependency>	
	<!-- 
			swagger相关的依赖
	 -->
	 <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
	<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.4.0</version>
</dependency>

	 <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
	<dependency>
	    <groupId>io.springfox</groupId>
	    <artifactId>springfox-swagger2</artifactId>
	<version>2.4.0</version>
	</dependency>
	 
	 
	<!--  
			日志相關依賴
	-->
	 <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
	<dependency>
	    <groupId>org.slf4j</groupId>
	    <artifactId>slf4j-api</artifactId>
	    <version>2.0.0-alpha1</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
	<dependency>
	    <groupId>org.slf4j</groupId>
	    <artifactId>slf4j-log4j12</artifactId>
	    <version>2.0.0-alpha1</version>
	</dependency>
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
	<dependency>
	    <groupId>log4j</groupId>
	    <artifactId>log4j</artifactId>
	    <version>1.2.17</version>
	</dependency>


  </dependencies>
  
  
  <build>
     	<!-- 配置定义版本插件 -->	 
	    <plugins>
	     <!-- tomcat插件控制 -->
		<plugin>
		    <groupId>org.apache.tomcat.maven</groupId>
		    <artifactId>tomcat7-maven-plugin</artifactId>
		    <version>2.2</version>
		    <configuration>
                <!--端口控制-->
				<port>8080</port>
                <!--项目路径控制意味着http://localhost:8080/abc-->
				<path>/</path>
                <!--编码-->
				<uriEncoding>UTF-8</uriEncoding>
			</configuration>
		</plugin>    
	    <!-- 定义jdk版本插件 --> 	    
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
	    </plugins>
 
	 	<!-- mapper扫描插件 -->   
	 	<resources>
	 		<resource>
	 			<directory>src/main/java</directory>
	 			<includes>
	 				<include>**/*.xml</include>
	 			</includes>
	 		</resource>
	 	</resources>	
 	
  </build>
</project>
           

2.MVC的配置文件spring_mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd 
	http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd ">

	<!-- 配置扫描类 -->
	<context:component-scan base-package="com.self.spring.swagger.controller"/>
	
	<!-- 开启注解支持 -->
	<mvc:annotation-driven/>
	
	<!-- 配置试图解析器 Internal:内部-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    	<property name="suffix" value=".jsp"/>
    	<property name="prefix" value="/"/> 	
    </bean>
   	
	<!-- 
			配置swagger相关的支持
	 -->
	<mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
	<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
	<!-- 静态资源交由默认的servlet处理 -->
	<mvc:default-servlet-handler/>
	
	<!-- 将swagger对应的配置类添加到IOC容器中 -->
	<bean class="com.self.spring.swagger.config.SwaggerConfig"/>
</beans>
           

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
				 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
				xmlns="http://java.sun.com/xml/ns/javaee" 
				xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
				xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
				http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>Archetype Created Web Application</display-name>
  
  <!--
  		1. 初始化spring容器,把springIOC容器交给springMVC管理
   -->
 <!--  <context-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:spring_applicationContext.xml</param-value>
  </context-param>
  初始化spring容器,优先于dispatchsevlet执行,将spring容器加载完成后保存到servletcontext 容器中
  <listener>
  		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
   -->
  <!--
  		 配置注册前段控制器dispatchservlet
  		 必须 注册前端控制器
  -->
  <servlet>
  	<servlet-name>spring_swagger</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<!-- 关联配置文件 -->
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  	    <param-value>classpath:spring_mvc.xml</param-value> 		
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>spring_swagger</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 
  配置 字符过滤器 ;    需要注意的是配置的时候,每个 标签都得按照顺序来,要不是会报错无法通过
    -->    
  <filter>
  <filter-name>encodingFilter</filter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>utf-8</param-value>
  	</init-param>
  	<init-param>
  <!-- 	响应编码方式开启 -->
  		<param-name>forceResponseEncoding</param-name>
  		<param-value>true</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>encodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
</web-app>

           

3.swagger的配置类:

package com.self.spring.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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;

@Configuration
@EnableSwagger2//放开swagger的支持
public class SwaggerConfig {

	/**
	 *    覆盖swagger默认的配置
	 */
	@Bean
	public Docket getDocket1() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.groupName("A")
				.select()
				.apis(RequestHandlerSelectors.basePackage("com.self.spring.swagger.controller.user"))
				.build();		
	}
	
	@Bean
	public Docket getDocket2() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				//分组名(有利于api的管理和分辨),组名必须是英文的
				.groupName("B")
				//为api选择启动生成器
				.select()
				//定义api对应的扫描包,生成对应api接口
				.apis(RequestHandlerSelectors.basePackage("com.self.spring.swagger.controller.dept"))
				.build();
	}
	
	/** 自定义显示头信息
	 * 
	 * @Title: apiInfo   
	 */
	private ApiInfo apiInfo() {
		Contact DEFAULT_CONTACT=new Contact("guanjun.zhou", "www.baidu.com", "[email protected]");
		return new ApiInfo("spring swagger 练习", 
				"swagger 测试",
				"2.0", 
				"urn:tos",
				DEFAULT_CONTACT, 
				"Apache 2.0",
				"https://www.apache.org/licenses/LICENSE-2.0");
	}
}
           

4.控制层注解的使用:

package com.self.spring.swagger.controller.user;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.self.spring.swagger.user.User;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

//@Controller
//@RequestMapping("/user")
@RestController
@Api(tags = "用户控制层")//描述显示的api类名
public class UserController {

	@GetMapping("/user/hello")
	@ApiIgnore//起到忽略的该方法显示的作用
	public String Hello() {
		System.out.println("hello world。。。");
		return "index";
	}
	
	@PostMapping("/user/query")
	@ApiOperation("查询用户信息")//方法名的显示设置
	//@ApiParam描述参数的内容信息
	public User query(@ApiParam("用户信息") @RequestBody User u) {
		System.out.println("query......."+u);
		
		User user=new User();
		user.setId(123);
		user.setName("张来");
		user.setAge(22);
		
		return new User();
	}
}
           

5.实体类注解的使用

package com.self.spring.swagger.user;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value = "用户bean")//描述响应显示的实体类的信息
public class User {

	@ApiModelProperty("用户的对应的ID")//用于对显示的属性的描述
	private int id;
	@ApiModelProperty("用户的对应的名称")
	private String name;
	@ApiModelProperty("用户的对应的年龄")
	private Integer age;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	
}
           

6.测试结果

spring整合swagger的案例

继续阅读