Bean定义由AutoConfiguration覆盖

时间:2018-05-08 12:11:52

标签: java spring spring-boot

在我的Spring应用程序中,我定义了一个类型为AuditListener的bean。

@Component
public class AuditListener {
}

我的项目还包含对spring-boot-starter-actuator的依赖,它还通过AuditListener定义了AuditAutoConfiguration类型的bean。

当我尝试启动我的应用程序时,它失败了,因为我自己的AuditListener不可用。

// successful
beanFactory.getBean(org.springframework.boot.actuate.audit.listener.AuditListener.class);

// fails with NoSuchBeanDefinitionException
beanFactory.getBean(demo.AuditListener.class);

例外:

java.lang.IllegalStateException: Failed to execute ApplicationRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:791)
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:778)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:335)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243)
    at demo.DemoApplication.main(DemoApplication.java:14)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'demo.AuditListener' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:347)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:334)
    at demo.DemoApplication.run(DemoApplication.java:27)
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:788)
    ... 11 more

DefaultListableBeanFactory记录

  

INFO 10140 --- [main] o.s.b.f.s.DefaultListableBeanFactory   :覆盖bean' auditListener'的bean定义与众不同   definition:replacement [Generic bean:class [demo.AuditListener];   范围=单;抽象= FALSE; lazyInit = FALSE; autowireMode = 0;   dependencyCheck = 0; autowireCandidate = TRUE;初级= FALSE;   factoryBeanName = NULL; factoryMethodName = NULL; initMethodName = NULL;   destroyMethodName = NULL;在文件中定义   [C:\工作空间\弹簧自动配置冲突-演示\目标\类\演示\ AuditListener.class]]   用[Root bean:class [null];范围=;抽象= FALSE; lazyInit = FALSE;   autowireMode = 3; dependencyCheck = 0; autowireCandidate = TRUE;   初级= FALSE;   factoryBeanName = org.springframework.boot.actuate.autoconfigure.audit.AuditAutoConfiguration;   factoryMethodName = auditListener; initMethodName = NULL;   destroyMethodName =(推断);在类路径资源中定义   [组织/ springframework的/启动/致动/自动配置/审计/ AuditAutoConfiguration.class]]

如何在不重命名自己的情况下将两个AuditListener bean添加到我的上下文中?

编辑:如果我在不同的包中定义了两个具有相同类名的bean,我会得到一个ConflictingBeanDefinitionException,因此ApplicationContext甚至不会启动。

2 个答案:

答案 0 :(得分:1)

您可以为bean命名,以便它不会与SpringBoot bean

冲突
@Component(value = "myCustomAuditListener ")
public class AuditListener {
}

然后使用@Qualifies按名称myCustomAuditListener

注入它

答案 1 :(得分:0)

如果 AutoConfiguration 添加了一个具有相同 bean 名称的 bean,Spring 将从上下文中删除您自己的 bean。这是标准的 Spring Framework 行为。当有多个 bean 声明为同名时,最后一个声明的将获胜。框架应该记录一条信息消息,让您知道已经发生了覆盖。

相关问题