出现问题的项目算是一个新项目,但基本的脚手架代码是从另一个项目里迁过来的,原项目并没有报错,只有新项目才报异常。看报错内容,判断发生冲突的主要是spring-boot-starter-security和springfox-swagger2这两个jar包的文件。

  新项目错误如下:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
15:22:32.350 spotcheck-system [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter - ***************************
APPLICATION FAILED TO START
*************************** Description: Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a single bean, but 2 were found:
- requestMappingHandlerMapping: defined by method 'requestMappingHandlerMapping' in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]
- swagger2ControllerMapping: defined by method 'swagger2ControllerMapping' in class path resource [springfox/documentation/swagger2/configuration/Swagger2DocumentationConfiguration.class] Action: Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping' available: expected single matching bean but found 2: requestMappingHandlerMapping,swagger2ControllerMapping

  我的项目中出错代码是这一行,在原项目并没有报错。

Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();

  getBean方法默认是byType来加载bean对象的,如果取到相同类型的2个就会报错。我分别查看了错误中提示的DelegatingWebMvcConfiguration.class和Swagger2DocumentationConfiguration.class。

  1. DelegatingWebMvcConfiguration.class里并没有requestMappingHandlerMapping方法,DelegatingWebMvcConfiguration继承了WebMvcConfigurationSupport.class类,在WebMvcConfigurationSupport.class类中有requestMappingHandlerMapping方法,返回值是RequestMappingHandlerMapping.class。代码如下:

    /**
* Return a {@link RequestMappingHandlerMapping} ordered at 0 for mapping
* requests to annotated controllers.
*/
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping mapping = createRequestMappingHandlerMapping();
......
}

  2. Swagger2DocumentationConfiguration.class里有swagger2ControllerMapping方法如下:

  @Bean
public HandlerMapping swagger2ControllerMapping(
Environment environment,
DocumentationCache documentationCache,
ServiceModelToSwagger2Mapper mapper,
JsonSerializer jsonSerializer) {
return new PropertySourcedRequestMappingHandlerMapping(environment, new Swagger2Controller(environment, documentationCache, mapper, jsonSerializer));
}

  这个方法里的返回值类型PropertySourcedRequestMappingHandlerMapping继承了RequestMappingHandlerMapping类,

public class PropertySourcedRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
......
}

  所以可能Spring加载时,根据byType形式会认错了吧。

  解决办法:既然Spring加载时使用byType形式会报错,那我们就用byName形式加载。Spring中使用@Bean声明的方法,如果没有指定名称,默认的name就是方法名。所以我们把出错代码改成:

        RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) applicationContext.getBean("requestMappingHandlerMapping");
Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = requestMappingHandlerMapping.getHandlerMethods();

  到此问题解决。

补充一下:

  假设自己项目中有一个接口,同时有两个实现类,并且实现类都使用了@Service注解,你在使用过程中使用了@Autowired注解进行引用。这时Spring初始化时就会报错:expected single matching bean but found 2 ,因为@Autowired默认是byType形式加载的。

  解决办法就是用@Primary、@Qualifier这两个注解来解决问题。

  @Primary注解是用来声明2个实现类那个是主要的。与@Component、@Service等注解放到一起使用。这时Spring通过@Autowired加载时,就会判断一下, 优先使用@Primary注解的类。

  @Qualifier显示声明加载类的名称,与@Autowired放到一起使用,这样Spring加载时判断类型相同,会在通过名称筛选出需要的类,就不会报错了。其实@Autowired + @Qualifier = @Resource,如果真需要byName形式加载,直接使用@Resource就可以了。

Spring Security和Swagger2集成报错的更多相关文章

  1. Spring Security 无法登陆,报错:There is no PasswordEncoder mapped for the id “null”

    编写好继承了WebSecurityConfigurerAdapter类的WebSecurityConfig类后,我们需要在configure(AuthenticationManagerBuilder ...

  2. 使用CXF+Spring发布WebService,启动报错

    使用CXF+Spring发布WebService,启动报错,日志如下: 五月 12, 2017 9:01:37 下午 org.apache.tomcat.util.digester.SetProper ...

  3. eclipes的Spring注解SequenceGenerator(name="sequenceGenerator")报错的解决方式

    eclipes的Spring注解SequenceGenerator(name="sequenceGenerator")报错的解决方式 右键项目打开Properties—>JA ...

  4. 【spring mvc】后台spring mvc接收List参数报错如下:org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.List]: Specified class is an interface

    后台spring mvc接收List参数报错如下:org.springframework.beans.BeanInstantiationException: Failed to instantiate ...

  5. spring boot启动STS 运行报错 java.lang.NoClassDefFoundError: ch/qos/logback/classic/LoggerContext

    spring boot启动STS 运行报错 java.lang.NoClassDefFoundError: ch/qos/logback/classic/LoggerContext 学习了: http ...

  6. Spring Boot 整合Spring Security 和Swagger2 遇到的问题小结

    How to configure Spring Security to allow Swagger URL to be accessed without authentication @Configu ...

  7. 笔记本电脑切换到无线热点无法联网问题&Spring Cloud相关工程启动报错问题

    通过禁用本地网络,和禁用另一个无线网络,以及禁用后重开,修改密码,重连的方式均失败后, 使用IE浏览器浏览提示失败,点击诊断,诊断出DNS服务器无响应异常. 突然想到通过ipconfig查看ip,网关 ...

  8. Spring Cloud和eureka启动报错 解决版本依赖关系

    导读 An attempt was made to call a method that does not exist. The attempt was made from the following ...

  9. 【Spring实战】—— 12 AspectJ报错:error at ::0 can't find referenced pointcut XXX

    今天在使用AspectJ进行注解切面时,遇到了一个错误. 切点表达式就是无法识别——详细报错信息如下: Exception can't find referenced pointcut perform ...

随机推荐

  1. plus.runtime.quit()是个好函数

    对于H5+APP开发,应用的生命周期监听函数里是对应用行为的监控,但是并不对应用执行退出或重启操作.相关操作还是要使用mui

  2. 选课系统<基于面向过程\对象>

    2020-04-15 00:09:28 程序目录: import os BASE_PATH=os.path.dirname(os.path.dirname(__file__)) DB_PATH=os. ...

  3. postman设置页面详解

    设置详解/General Trim keys and values in request body:如果使用form-data或者url-encoded的方式向服务器发送数据:将该选项设置为ON,则会 ...

  4. [JAVA]移位运算(左移<<,右移>>和无符号右移>>>)

    一.背景知识 整数在内存中是以二进制的形式存在的,而且存的是该整数的补码.最高位代表符号位,正数为0,负数为1 正数的补码是其二进制本身,负数的补码则是 符号位保持1不变,其他位按位取反再加1,+0和 ...

  5. SpringBoot执行定时任务@Scheduled

    SpringBoot执行定时任务@Scheduled 在做项目时,需要一个定时任务来接收数据存入数据库,后端再写一个接口来提供该该数据的最新的那一条. 数据保持最新:设计字段sign的值(0,1)来设 ...

  6. DVWA学习记录 PartⅠ

    DVWA介绍 DVWA(Damn Vulnerable Web Application)是一个用来进行安全脆弱性鉴定的PHP/MySQL Web应用,旨在为安全专业人员测试自己的专业技能和工具提供合法 ...

  7. Scala 基础(十五):Scala 模式匹配(三)

    1 变量声明中的模式 match中每一个case都可以单独提取出来,意思是一样的. 应用案例 val (x, y) = (1, 2) val (q, r) = BigInt(10) /% 3 //说明 ...

  8. The Modules of Event-driven

    常用的时间驱动模型(Windows和Linux都有)有三种: 1.select 对于读(Read)事件.写(Write)事件和异常(Exception)事件分别创建事件描述符集合,分别用来收集读事件的 ...

  9. 基于.NetCore3.1系列 ——认证授权方案之Swagger加锁

    一.前言 在之前的使用Swagger做Api文档中,我们已经使用Swagger进行开发接口文档,以及更加方便的使用.这一转换,让更多的接口可以以通俗易懂的方式展现给开发人员.而在后续的内容中,为了对a ...

  10. P1136 迎接仪式 题解

    题目描述 LHX教主要来X市指导OI学习工作了.为了迎接教主,在一条道路旁,一群Orz教主er穿着文化衫站在道路两旁迎接教主,每件文化衫上都印着大字.一旁的Orzer依次摆出"欢迎欢迎欢迎欢 ...