SpringMVC与Springfox(Swagger2)整合详解以及涉及的问题处理

        Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。

 作用:

         1. 接口的文档在线自动生成。

        2. 功能测试。

       在做Spring+SpringMVC+Mybatis的项目中整合Springfox(Swagger2)。  在网上查看了很多的资料,遇到了好多坑点,摸索了多半天,总算是成功的整合了。现在记录一下成果,希望能给有需求的朋友提供参考,就可以早点回家吃饭了

        今天不讲SSM整合,是在这个基础上整合springfox,我的Spring版本是4.0.9.RELEASE,springfox用的是2.4.0(spring版本要和springfox对应,高版本的springfox里面有些方法低版本的Spring没有,我们工作环境是spring4.0.9,所以为以下示例,但是spring4.3.5+与springfox2.7.0整合也是可以的),如果使用FastJson的话版本得在1.2.10以上(不然http://localhost:8080/v2/api-docs返回为空),我用的是1.2.30。

 

1、在maven的pom文件中引入springfox的依赖

		<!-- swagger -->
		<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>
                <dependency>  
                    <groupId>com.fasterxml.jackson.core</groupId>  
                    <artifactId>jackson-databind</artifactId>  
                    <version>2.6.3</version>  
                </dependency>  
                <!-- FastJson的版本必须在1.2.10以上-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.30</version>
		</dependency>

2、在源码目录下创建一个单独的package,然后创建Swagger2Config.java文件

package com.common;
 
import org.springframework.context.annotation.Bean;
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;
 
@EnableSwagger2
public class Swagger2Config {
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
			.apiInfo(apiInfo())
  			.enable(true)  //是否启用Swagger
			.select()
			.apis(RequestHandlerSelectors.basePackage("com.group.controller")) //扫描的包
			.paths(PathSelectors.any())
			.build();
	}
 
	private ApiInfo apiInfo() {
 
		return new ApiInfoBuilder()
			.title("xxx测试服务API")
			.description("杭州xx网络科技@API")
			.termsOfServiceUrl("http://xxx.cc/")
			.license("© 2018-chenwei. All rights reserved.")
			.version("1.0")
			.build();
	}
}

3、在springMVC的配置文件中配置swagger

	<!--添加swagger2配置-->
	<!-- API访问地址:http://ip:port/swagger-ui.html -->
	<bean class="com.common.Swagger2Config" />
	<mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
	<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>

4、修改web.xml文件中配置所有的请求都经DispatcherServlet处理

<servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

注意:这个地方必须配置,如果你配置的是*.XXX的形式会出现api-docs访问出错,这就会导致swagger-ui找不到api的有效路径。使swagger无法正常工作 

5、controller的配置,这里我只做简单的配置测试swagger是否正常工作

启动项目:能够正常的工作

已标记关键词 清除标记
``` ## //主控制器 package com.miaoshaproject; import com.miaoshaproject.dao.UserDOMapper; import com.miaoshaproject.dataobject.UserDO; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * Hello world! * */ @SpringBootApplication(scanBasePackages = {"com.miaoshaproject"}) @RestController @MapperScan("com.miaoshaproject.dao") public class App { @Resource private UserDOMapper userDOMapper; @RequestMapping("/") public String home(){ UserDO userDO = userDOMapper.selectByPrimaryKey(1); if(userDO==null){ return "用户对象不存在"; }else{ return userDO.getName(); } } public static void main( String[] args ) { System.out.println("Hello World!"); SpringApplication.run(App.class,args); } } ``` ``` ## DAO package com.miaoshaproject.dao; import com.miaoshaproject.dataobject.UserDO; import org.springframework.stereotype.Repository; public interface UserDOMapper { UserDO selectByPrimaryKey(Integer id); } ``` ``` ## mapper.xml文件 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.miaoshaproject.dao.UserDOMapper"> <resultMap id="BaseResultMap" type="com.miaoshaproject.dataobject.UserDO"> <!-- WARNING - @mbg.generated This element is automatically generated by MyBatis Generator, do not modify. This element was generated on Mon Apr 06 17:07:07 CST 2020. --> <id column="id" jdbcType="INTEGER" property="id" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="gender" jdbcType="TINYINT" property="gender" /> <result column="age" jdbcType="INTEGER" property="age" /> <result column="telphone" jdbcType="VARCHAR" property="telphone" /> <result column="register-mode" jdbcType="VARCHAR" property="registerMode" /> <result column="third_party_id" jdbcType="VARCHAR" property="thirdPartyId" /> </resultMap> <sql id="Base_Column_List"> <!-- WARNING - @mbg.generated This element is automatically generated by MyBatis Generator, do not modify. This element was generated on Mon Apr 06 17:07:07 CST 2020. --> id, name, gender, age, telphone, register-mode, third_party_id </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from user_info where id = #{id,jdbcType=INTEGER} </select> </mapper> ``` ``` ## 配置文件 mybatis.mapper-locations=classpath:mapping/UserDOMapper.xml,classpath:mapping/UserPasswordDOMapper.xml server.port=8090 spring.datasource.name=miaosha spring.datasource.url=jdbc:mysql://localhost:3306/miaosha?characterEnconding=utf8&useSSL=true spring.data.cassandra.password=000000 spring.data.cassandra.username=root anagement.security.enabled=false #使用druid数据源 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driverClassName=com.mysql.jdbc.Driver ``` ``` 错误代码 [main] INFO com.miaoshaproject.App - Starting App on DESKTOP-HNHSR91 with PID 17804 (C:\Users\hasee\IdeaProjects\miaosha\target\classes started by hasee in C:\Users\hasee\IdeaProjects\miaosha) [main] INFO com.miaoshaproject.App - No active profile set, falling back to default profiles: default [main] INFO org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1d8d30f7: startup date [Wed Apr 08 11:38:09 CST 2020]; root of context hierarchy [main] INFO org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring [main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'app': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDOMapper' defined in file [C:\Users\hasee\IdeaProjects\miaosha\target\classes\com\miaoshaproject\dao\UserDOMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration': Unexpected exception during bean creation; nested exception is java.lang.TypeNotPresentException: Type org.apache.ibatis.mapping.DatabaseIdProvider not present [main] INFO org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener - Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. [main] ERROR org.springframework.boot.SpringApplication - Application run failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'app': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDOMapper' defined in file [C:\Users\hasee\IdeaProjects\miaosha\target\classes\com\miaoshaproject\dao\UserDOMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration': Unexpected exception during bean creation; nested exception is java.lang.TypeNotPresentException: Type org.apache.ibatis.mapping.DatabaseIdProvider not present at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:321) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1277) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1265) at com.miaoshaproject.App.main(App.java:39) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDOMapper' defined in file [C:\Users\hasee\IdeaProjects\miaosha\target\classes\com\miaoshaproject\dao\UserDOMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration': Unexpected exception during bean creation; nested exception is java.lang.TypeNotPresentException: Type org.apache.ibatis.mapping.DatabaseIdProvider not present at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1436) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1323) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:514) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:485) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:619) at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:180) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:318) ... 16 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration': Unexpected exception during bean creation; nested exception is java.lang.TypeNotPresentException: Type org.apache.ibatis.mapping.DatabaseIdProvider not present at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:508) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1247) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1096) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1421) ... 29 more Caused by: java.lang.TypeNotPresentException: Type org.apache.ibatis.mapping.DatabaseIdProvider not present at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:117) at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125) at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49) at sun.reflect.generics.visitor.Reifier.reifyTypeArguments(Reifier.java:68) at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:138) at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49) at sun.reflect.generics.repository.ConstructorRepository.getParameterTypes(ConstructorRepository.java:94) at java.lang.reflect.Executable.getGenericParameterTypes(Executable.java:283) at java.lang.reflect.Constructor.getGenericParameterTypes(Constructor.java:234) at org.springframework.core.MethodParameter.getGenericParameterType(MethodParameter.java:423) at org.springframework.core.SerializableTypeWrapper$MethodParameterTypeProvider.getType(SerializableTypeWrapper.java:317) at org.springframework.core.SerializableTypeWrapper.forTypeProvider(SerializableTypeWrapper.java:137) at org.springframework.core.ResolvableType.forType(ResolvableType.java:1384) at org.springframework.core.ResolvableType.forMethodParameter(ResolvableType.java:1285) at org.springframework.core.ResolvableType.forMethodParameter(ResolvableType.java:1251) at org.springframework.beans.factory.config.DependencyDescriptor.getResolvableType(DependencyDescriptor.java:290) at org.springframework.beans.factory.support.GenericTypeAwareAutowireCandidateResolver.checkGenericTypeMatch(GenericTypeAwareAutowireCandidateResolver.java:76) at org.springframework.beans.factory.support.GenericTypeAwareAutowireCandidateResolver.isAutowireCandidate(GenericTypeAwareAutowireCandidateResolver.java:68) at org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolver.isAutowireCandidate(QualifierAnnotationAutowireCandidateResolver.java:147) at org.springframework.beans.factory.support.DefaultListableBeanFactory.isAutowireCandidate(DefaultListableBeanFactory.java:674) at org.springframework.beans.factory.support.DefaultListableBeanFactory.isAutowireCandidate(DefaultListableBeanFactory.java:631) at org.springframework.beans.factory.support.DefaultListableBeanFactory.isAutowireCandidate(DefaultListableBeanFactory.java:615) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1287) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1098) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:818) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:724) at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:197) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1267) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1124) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) ... 46 more Caused by: java.lang.ClassNotFoundException: org.apache.ibatis.mapping.DatabaseIdProvider at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:348) at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114) ... 77 more Process finished with exit code 1 ``` 这个问题困扰我很久了,在网上搜索了mapper文件重复或者换@Resource都没有解决,麻烦各位同学老师帮忙看看,谢谢! 本人在线等待大佬们的帮忙,比较急被卡很多天了。
环境sprin4 , jdk 1.8 org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component c lass: file [D:\workspace_Resin\App\target\classes\cn\activity\service\UserProfileServi ce.class]; nested exception is java.lang.IllegalArgumentException at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCa ndidateComponents(ClassPathScanningCandidateComponentProvider.java:281) at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBea nDefinitionScanner.java:242) at org.springframework.context.annotation.ComponentScanBeanDefinitionParser.parse(ComponentS canBeanDefinitionParser.java:84) at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSuppo rt.java:73) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(Bea nDefinitionParserDelegate.java:1438) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(Bea nDefinitionParserDelegate.java:1428) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefini tions(DefaultBeanDefinitionDocumentReader.java:184) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanD efinitions(DefaultBeanDefinitionDocumentReader.java:140) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDef initions(DefaultBeanDefinitionDocumentReader.java:111) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(Xml BeanDefinitionReader.java:493) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBe anDefinitionReader.java:390) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBean DefinitionReader.java:334) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBean DefinitionReader.java:302) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinition s(AbstractBeanDefinitionReader.java:174)
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页