【发布时间】:2023-04-08 11:58:01
【问题描述】:
我的项目设置如下。
如图所示,我有一个辅助项目(带有 2 个 @Autowired 时钟),而我的主项目带有 1 个 @Autowired 时钟。所有三个时钟都表示同一个对象。
当我启动应用程序时,我收到错误:
org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“helper2”的 bean 时出错:不满足的依赖关系 通过字段“时钟”表示;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 可用的“java.time.Clock”类型的合格bean:至少预期 1 个有资格作为自动装配候选者的 bean。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE] 在 org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
.
.
.
.
~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE] 原因: org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 可用的“java.time.Clock”类型的合格bean:至少预期 1 个有资格作为自动装配候选者的 bean。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1506) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE] 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1101) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
【问题讨论】:
-
你如何提供你的bean定义?通过 .xml 文件?如我所见,您有
MainConfig.class,其中定义了@Bean,但在这种情况下,该类需要标记为@Configuration。 -
在主配置中,您将时钟类型的 bean 和自动装配定义为类成员。为什么你需要@autowired 时钟?
-
你有一个循环依赖。
-
谢谢 Devdio。我没有使用 xml 文件。我用 @Configuration 标记了我的 MainConfig,但我得到了同样的错误。
-
感谢您的回复 Himanshu。我已经从 MainConfig 中删除了 Autowired。 MainConfig 只有方法,@Bean public Clock getClock() { return Clock.systemDefaultZone(); Helper2 和 Helper3 具有 Autowired Clock 时钟注释。仍然是同样的错误。
标签: java spring spring-boot exception autowired