Spring Security和Swagger2集成报错
出现问题的项目算是一个新项目,但基本的脚手架代码是从另一个项目里迁过来的,原项目并没有报错,只有新项目才报异常。看报错内容,判断发生冲突的主要是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集成报错的更多相关文章
- Spring Security 无法登陆,报错:There is no PasswordEncoder mapped for the id “null”
编写好继承了WebSecurityConfigurerAdapter类的WebSecurityConfig类后,我们需要在configure(AuthenticationManagerBuilder ...
- 使用CXF+Spring发布WebService,启动报错
使用CXF+Spring发布WebService,启动报错,日志如下: 五月 12, 2017 9:01:37 下午 org.apache.tomcat.util.digester.SetProper ...
- eclipes的Spring注解SequenceGenerator(name="sequenceGenerator")报错的解决方式
eclipes的Spring注解SequenceGenerator(name="sequenceGenerator")报错的解决方式 右键项目打开Properties—>JA ...
- 【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 ...
- spring boot启动STS 运行报错 java.lang.NoClassDefFoundError: ch/qos/logback/classic/LoggerContext
spring boot启动STS 运行报错 java.lang.NoClassDefFoundError: ch/qos/logback/classic/LoggerContext 学习了: http ...
- Spring Boot 整合Spring Security 和Swagger2 遇到的问题小结
How to configure Spring Security to allow Swagger URL to be accessed without authentication @Configu ...
- 笔记本电脑切换到无线热点无法联网问题&Spring Cloud相关工程启动报错问题
通过禁用本地网络,和禁用另一个无线网络,以及禁用后重开,修改密码,重连的方式均失败后, 使用IE浏览器浏览提示失败,点击诊断,诊断出DNS服务器无响应异常. 突然想到通过ipconfig查看ip,网关 ...
- Spring Cloud和eureka启动报错 解决版本依赖关系
导读 An attempt was made to call a method that does not exist. The attempt was made from the following ...
- 【Spring实战】—— 12 AspectJ报错:error at ::0 can't find referenced pointcut XXX
今天在使用AspectJ进行注解切面时,遇到了一个错误. 切点表达式就是无法识别——详细报错信息如下: Exception can't find referenced pointcut perform ...
随机推荐
- Python axis的含义
axis=0表述列 axis=1表述行 如下面例子: In [52]: arr=np.arange(12).reshape((3,4))In [53]:arrOut[53]:array([[ 0, 1 ...
- HLS的M3U8文件介绍
HLS的M3U8文件介绍 HLS (HTTP Live Streaming)是Apple的动态码率自适应技术.主要用于PC和Apple终端的音视频服务. 相较于实时传输协议(RTP),HLS可以穿过任 ...
- Go的100天之旅-04基础数据类型
基础数据类型 在变量的定义中,我们讲了每个变量是有类型的,类型在计算机中是用来约束数据的解释.Go语言和其它计算机语言一样,提供丰富了丰富的数据类型,我们就来看看到底有哪些类型,同时也可以比较一下它和 ...
- OSCP Learning Notes - Enumeration(3)
SMB Enumeration 1. Set the smb configurations. locate smb.conf vim /etc/samba/smb.conf Insert the gl ...
- 微信小程序开发部署
一.开发准备 1,想要开发微信小程序,必须要有一个AppId,如果没有可以去注册一个. https://mp.weixin.qq.com/进入注册页面,点击上方注册. 2,点击选择“小程序”出 ...
- Shell基本语法---shell数组
shell数组 arr=( ) #定义数组 echo ${#arr[*]} #打印数组长度 echo ${arr[]} #打印数组的第一个成员 echo ${arr[]} #打印数组的二个成员 ech ...
- abp vnext 开发快速入门 2 实现基本增删改查
上篇说了abp vnext 的大体框架结构,本篇说下如何实现基础的增删改查.实现增删改查有以下几个步骤: 1.配置数据库连接 2.领域层(Domain)创建实体,Ef core 层配置Dbset( 用 ...
- java代码之美(17) ---Java8 LocalDateTime
Java8 LocalDateTime 在java8之前我们在处理时间的时候都是用的Date,但它其实有很明显的缺点. 1.我们也会对日期做一些操作,比如加几天.加几分,当月的最后一天等等.有些计算实 ...
- web自动化 -- HTMLreport(二)测试报告输出内容居左对齐
一.需求痛点 1.报告输出内容是居中对齐,很难看 2.我们希望输出内容是居左对齐 3.痛点截图 二.解决办法 1.原因分析 HTMLreport的内容对齐方式,自然是修改HTMLreport的内容了 ...
- vue学习(六) 事件修饰符 stop prevent capture self once
//html <div id="app"> <div @click="divHandler" style="height:150px ...