栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring中Bean重复注入问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring中Bean重复注入问题

Spring重复注入同一个bean问题 冲突的依赖包

其实本质上只是easypoi:4.0.0这个jar自己就会发生冲突,主要是下面两个类之间的冲突

 
 	cn.afterturn
 	easypoi-spring-boot-starter
 	4.0.0
 
 
 		
 	org.springframework.boot
	spring-boot-starter 
 	2.4.4
 
错误描述
The bean 'beanNameViewResolver', defined in class path resource [cn/afterturn/easypoi/configuration/EasyPoiAutoConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class] and overriding is disabled.
寻找原因根据提示解决问题

找到easypoi-spring-boot-starter:4.0.4的中cn.afterturn.easypoi.configuration.EasyPoiAutoConfiguration类中方法beanNameViewResolver注入BeanNameViewResolver类型的Bean

@Bean
public BeanNameViewResolver beanNameViewResolver() {
    BeanNameViewResolver resolver = new BeanNameViewResolver();
    resolver.setOrder(10);
    return resolver;
}

再找到spring-boot-autoconfigure:2.4.4中org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration中的内部类WhitelabelErrorViewConfiguration中有方法beanNameViewResolver注入BeanNameViewResolver类型的bean

@Bean
@ConditionalOnMissingBean
 public BeanNameViewResolver beanNameViewResolver() {
     BeanNameViewResolver resolver = new BeanNameViewResolver();
     resolver.setOrder(2147483637);
     return resolver;
 }

经过我一番查找发现这两个方法注入的是同一个org.springframework.web.servlet.view.BeanNameViewResolver类型的bean,该bean在spring-webmvc-5.3.5.jar下。springboot给出了解决重复注入bean的提示如下

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

大致意思是说在配置文件中开启同一个bean重复注入时与许最后一个注入的bean覆盖掉前面的注入的bean
后来在bean文件中加入如下配置

spring:
  main:
    allow-bean-definition-overriding: true    # 开启一样的bean的覆盖注入,后定义的bean会覆盖之前定义的相同名称的bean。

加入该配置后项目启动成功。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/424766.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号