Spring mvc + mybatis+maven集成swagger ui自动生成api文档
最近由于项目需要所以需要集成swagger-ui这货进行api文档自动生成的功能,才去研究了好久,当然也踩了很多坑,算是总结了一些经验,希望可以帮助需要的同学少走弯路吧!,本人语文估计没学好,有些表达或许不理想,那么可以点击【满级传送门】直接看源码!好了废话不多说了,直接上干货,开始干起来!
[Part 1]:构建Spring mvc+mybatis应用
你必须得已经构建好了一个web应用,而且这应用是可以跑起来的,就是可以从数据库获取数据返回到页面,或者从页面中可以提交数据到数据库的!这样的一个简单的架构应该没问题哈!
连接数据库配置文件(非web层)-spring-mybatis.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:mybatis="http://mybatis.org/schema/mybatis-spring"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 注入自动扫描非web层 -->
<context:component-scan base-package="org.com.swagger.code">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:property-placeholder location="classpath:config/jdbc.properties"/>
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 配置过滤 -->
<property name="filters" value="stat"/>
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="10"/>
<property name="minIdle" value="10"/>
<property name="maxActive" value="100"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000"/>
<!-- 检测连接是否有效的SQL -->
<property name="validationQuery" value="SELECT 'x'"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
</bean>
<!-- 扫描mapper映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.com.swagger.code.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
web层配置文件-spring-mvc-servlet.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"
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-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- 自動掃描web層bean -->
<context:component-scan base-package="org.com.swagger.code" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 開啟註解 -->
<context:annotation-config/>
<!-- 配置視圖 -->
<!-- <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="viewClass">
<value>org.springframework.web.servlet.view.freemarker.FreeMarkerView</value>
</property>
<property name="cache"><value>true</value></property>
<property name="prefix"><value>/WEB-INF/views/</value></property>
<property name="suffix"><value>.ftl</value></property>
<property name="contentType">
<value>text/html; charset=UTF-8</value>
</property>
</bean> -->
<mvc:annotation-driven />
<!-- swagger-ui配置java类 bean -->
<bean id="swaggerConfig" class="org.com.swagger.code.swagger.SwaggerConfig"/>
<!-- 自动注册的SimpleUrlHandlerMapping 获取资源部分 -->
<!-- servlet在找页面时,走的是dispatcherServlet路线。找不到的时候会报404加上这个默认的servlet时候,servlet在找不到的时候会去找静态的内容。 -->
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
<property name="contentType" value="text/html;charset=UTF-8"></property>
</bean>
<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="fastJsonHttpMessageConverter"
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="fastJsonHttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean>
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="UTF-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
<!-- FreeMarker中获取上下文路径 -->
<!-- <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/views/"/>
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">3</prop>
<prop key="defaultEncoding">UTF-8</prop>
<prop key="url_escaping_charset">UTF-8</prop>
<prop key="locale">zh_CN</prop>
<prop key="boolean_format">true,false</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="time_format">HH:mm:ss</prop>
<prop key="number_format">0.######</prop>
<prop key="whitespace_stripping">true</prop>
<prop key="classic_compatible">true</prop>
</props>
</property>
<property name="freemarkerVariables">
<map>
<entry key="webRoot" value="/vrum/"></entry>
</map>
</property>
</bean>-->
</beans>
servlet配置文件-web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-mybatis.xml</param-value>
</context-param>
<!-- 设计路径变量值 -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>springmvc.root</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<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>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<!-- 日志记录 -->
<context-param>
<!-- 日志配置文件路径 -->
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:config/log4j.properties</param-value>
</context-param>
<context-param>
<!-- 日志页面的刷新间隔 -->
<param-name>log4jRefreshInterval</param-name>
<param-value>6000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- spring mvc -->
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-mvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.ico</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.xls</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.doc</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
<!-- 字体相关 开始 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.eot</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.svg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.ttf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.woff</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.woff2</url-pattern>
</servlet-mapping>
<!-- 字体相关 结束 -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
好了,上面的配置已经可以构建一套简单的web应用的了,哦!对了 还有依赖包
maven-pom依赖文件-pom.xml
<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>swagger.code</groupId>
<artifactId>swagger-code</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>swagger-code Maven Webapp</name>
<url>http://mvnrepository.com/</url>
<!-- 版本控制 -->
<properties>
<asm.version>3.3.1</asm.version>
<javax.inject.version>1</javax.inject.version>
<spring.version>4.0.9.RELEASE</spring.version>
<jedis.version>2.7.3</jedis.version>
<mybatis.version>3.2.8</mybatis.version>
<mybatis-spring.version>1.2.2</mybatis-spring.version>
<mysql.version>5.1.26</mysql.version>
<druid.version>1.0.9</druid.version>
<log4j.version>1.2.17</log4j.version>
<slf4j.version>1.7.5</slf4j.version>
<poi.version>3.10-FINAL</poi.version>
<druid.version>1.0.15</druid.version>
<javax.annotation-api.version>1.2</javax.annotation-api.version>
<mail.version>1.4.7</mail.version>
<ezmorph.version>1.0.6</ezmorph.version>
<gson.version>2.8.0</gson.version>
<icu4j.version>3.4.4</icu4j.version>
<jpush-client.version>3.1.3</jpush-client.version>
<lombok.version>1.16.6</lombok.version>
<echarts.version>3.0.0</echarts.version>
<commons-net.version>3.4</commons-net.version>
<commons-lang3.version>3.1</commons-lang3.version>
<commons-io.version>2.4</commons-io.version>
<commons-codec.version>1.8</commons-codec.version>
<commons-fileupload.version>1.3.2</commons-fileupload.version>
<commons-beanutils.version>1.8.3</commons-beanutils.version>
<jackson-asl.version>1.9.13</jackson-asl.version>
<curator-framework.version>1.1.10</curator-framework.version>
<commons-pool2.version>2.4.2</commons-pool2.version>
<pjl-comp-filter.version>1.7</pjl-comp-filter.version>
<aspectjweaver.version>1.8.9</aspectjweaver.version>
<json-lib.version>2.4</json-lib.version>
<flexjson.version>3.3</flexjson.version>
<jaxen.version>1.1.1</jaxen.version>
<jdom.version>1.1</jdom.version>
<im4java.version>1.4.0</im4java.version>
<jsoup.version>1.8.3</jsoup.version>
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<javax.servlet.jsp-api.version>2.3.1</javax.servlet.jsp-api.version>
<bcprov-jdk15on.version>1.52</bcprov-jdk15on.version>
<jedis.version>2.7.3</jedis.version>
<ehcache-core.version>2.5.7</ehcache-core.version>
<ehcache-web.version>2.0.4</ehcache-web.version>
<spring-data-redis.vresion>1.5.2.RELEASE</spring-data-redis.vresion>
</properties>
<dependencies>
<!-- spring核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!--json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>${json-lib.version}</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>net.sf.flexjson</groupId>
<artifactId>flexjson</artifactId>
<version>${flexjson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${jackson-asl.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
<!-- Freemaker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<!-- javax提供的annotation -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>${javax.inject.version}</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- aop代理 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>net.sourceforge.pjl-comp-filter</groupId>
<artifactId>pjl-comp-filter</artifactId>
<version>${pjl-comp-filter.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxjava</artifactId>
<version>2.0.8</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>${commons-pool2.version}</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>${commons-net.version}</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>${commons-beanutils.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>${jaxen.version}</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>${jdom.version}</version>
</dependency>
<dependency>
<groupId>org.im4java</groupId>
<artifactId>im4java</artifactId>
<version>${im4java.version}</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bcprov-jdk15on.version}</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${javax.annotation-api.version}</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>${ezmorph.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>${icu4j.version}</version>
</dependency>
<!-- servlet api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${spring-data-redis.vresion}</version>
</dependency>
<dependency>
<groupId>de.ruedigermoeller</groupId>
<artifactId>fst</artifactId>
<version>2.05</version>
</dependency>
<!-- swagger-ui 核心包 -->
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>0.9.5</version>
</dependency>
</dependencies>
<build>
<finalName>swagger-code</finalName>
</build>
</project>
项目包结构图
到这里我相信你可以轻松的构建一个web应用了,并且是基于spring mvc + mybatis框架的啦!
[Part 2]:准备一套swagger-ui需要的静态文件
你还必须有一套swagger-ui的静态资源,比如:js、css、img等等,官网上提供的是github的下载地址,但是我试过并没卵用,所以我用的是一套15年的版本的文件,至少这套文件我跑起来了证明是可以用的!
首先先展示一下swagger-ui的文件结构
没错,你没看错,就是这么多文件,不然会出现一个Bug:No operations defined in spec!
这个bug相信你不陌生,这个bug就是因为ui静态资源缺省造成的(个人总结,如有误差轻喷)
[Part 3]:吹东风
好了上面已经把需要准备的都准备好了,只欠东风就能起大火了!
SwaggerConfig.java类,唯一一个需要在java后台中撰写的java类
package org.com.swagger.code.swagger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
@Configuration
@EnableSwagger
@EnableWebMvc
public class SwaggerConfig {
private SpringSwaggerConfig springSwaggerConfig;
/**
* Required to autowire SpringSwaggerConfig
*/
@Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
/**
* Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc
* framework - allowing for multiple swagger groups i.e. same code base
* multiple swagger resource listings.
*/
@Bean
public SwaggerSpringMvcPlugin customImplementation() {
// 暂时不用过滤
/**
* includePatterns:过去接口函数,通过正则可以过滤哪些接口不显示
*/
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo()).includePatterns(".*?");
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo(
"spring mvc 集成 swagger 文档工具",
"API文档集成工具",
"swagger-code",
"http://127.0.0.1:8080",
"aaa@qq.com",
"version 1.0.0"
);
return apiInfo;
}
}
上面的配置类写好了,这个类是干嘛用的呢,我个人探索发现这个类就是swagger-ui的一个配置文件,通过这个类swagger-ui可以扫描所有web层(即controller 或 action)进行数据解析,然后在swagger-ui的界面中以优美的方式以json格式形成文档!,注意上面的注解不可以省哦!
[Part 4]是时候收货了
万事大吉了,是该检测程序的正确性了,这个时候就可以弄个测试类进行测试了
swagger-ui测试controller
package org.com.swagger.code.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.com.swagger.code.constants.Constants;
import org.com.swagger.code.constants.Result;
import org.com.swagger.code.entity.User;
import org.com.swagger.code.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.sun.istack.internal.logging.Logger;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
@Api(value="/store",description="商店")
@Controller
@RequestMapping("user")
public class UserController {
private final Logger log = Logger.getLogger(UserController.class);
@Autowired
private UserService userService;
@RequestMapping(value="/get-user",method=RequestMethod.POST,produces={"application/json;charset=utf-8"})
@ResponseBody
public String getUser(HttpServletRequest req,HttpServletResponse res,@RequestParam int id){
Result<User> result = null;
User user = userService.getUser(id);
if(user != null){
result = new Result<User>(Constants.SUCCESS_CODE, Constants.SUCCESS_MSG, user);
}else{
result = new Result<User>(Constants.ERROR_CODE, Constants.ERROR_MSG);
}
return JSON.toJSONString(result);
}
@ResponseBody
@RequestMapping(value = "/view", method = RequestMethod.GET, produces = {"application/json; charset=utf-8","application/xml"})
@ApiOperation(value = "通过ID查询USER信息", httpMethod = "GET", notes = "通过ID查询USER信息")
public String getUserById(
@ApiParam(required = true, name = "id", value = "ID")
@RequestParam(value = "id") int id,HttpServletRequest request) {
log.info(String.format("at function, %s", id));
Result<User> result = null;
User user = userService.getUser(id);
if(user != null){
result = new Result<User>(Constants.SUCCESS_CODE, Constants.SUCCESS_MSG, user);
}else{
result = new Result<User>(Constants.ERROR_CODE, Constants.ERROR_MSG);
}
return JSON.toJSONString(result);
}
}
解释一下【@ApiOperation】 和 【@ApiParam】这俩货,本controller里面写有两个接口,一个getUser 和一个 getUserById,其实两个接口返回结果一模一样,进行一个有上面俩货一个没有,下面我们来来看结果对比一下:
【普通注解】
【加了@ApiOperation和@ApiParam这俩buff的】
[Part 4]疑点讲解
spring-mvc-servlet.xml文件中我添加了一个
<bean id="swaggerConfig" class="org.com.swagger.code.swagger.SwaggerConfig"/>
这样的一个bean对象,这个bean 应该就是用来获取web层应用的返回数据然后显示到静态页面中去,如果有兴趣可以看看swagger-springmvc的源代码去了解,综上,可以看出来需要我们手写的仅仅两个部分(属于springmvc + mybatis额外的部分):一个是swaggerConfig类 一个 swaggerConfig bean对象
运行swagger-ui,在运行前需要做一个小事情
- 把swagger-ui的静态资源中的index.html中的这一行代码稍微改一下
- $(function () {
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
//url = “http://petstore.swagger.io/v2/swagger.json“;
url = “http://127.0.0.1:8080/swagger-code/api-docs” ;//域名/项目名/api-docs
} - 域名=http://127.0.0.1:8080
- 项目名=swagger-code
好了,骚年们,可以扬帆起航了,亲自去试试感觉如何,以后再也不用为了写文档而心烦了!
上一篇: Go gin框架 使用swagger生成API文档
下一篇: 华为网络工程师 | 如何配置端口隔离?