【问题标题】:@Conditional annotation causing BeanCreationException on nested beans@Conditional 注释在嵌套 bean 上导致 BeanCreationException
【发布时间】:2018-10-31 12:52:04
【问题描述】:

我正在使用 Spring 4.x,其中我使用 @Conditional 注释来控制 bean 注册。 我有如下定义的类,

@Controller
class SchoolController{
   @Autowired
   @Qualifier("studentProcessor")
   private StudentProcessor studentProcessor;
   //Some code
}

@Component("studentProcessor")
class StudentProcessor{
   @Autiwired
   private SportService sportService;
   //Some code
}

@Component
@Conditional(ServiceCondition.class)
class SportService{
//Some code
}

class ServiceCondition implements Condition{
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
  //Some condition
}
}

当我启动 Tomcat 时,我得到了这个异常: org.springframework.beans.factory.BeanCreationException:创建名为“studentProcessor”的bean时出错:注入自动装配的依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:com.student.service.SportService com.student.processors.StudentProcessor.sportService;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到类型为 [com.student.service.SportService] 的合格 bean:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

  1. 这是预期的行为吗?
  2. 如果没有,我该如何解决这个问题?

【问题讨论】:

    标签: conditional spring-4 beancreationexception


    【解决方案1】:

    根据您的配置,SportService bean 是根据ServiceCondition 的条件实现加载的。

    因此,如果matches 方法基于您的逻辑出于某种原因返回false,则SportService 将不会被创建并且不能用于自动装配。

    话虽如此,StudentProcessor 不能为SportService 提供具体的@Autowired

    我不完全了解您的要求,但要继续进行此配置,您需要将自动装配标记为可选。

    @Autiwired
    private SportService sportService;
    //Some code
    

    @Autiwired(required = false)
    private SportService sportService;
    //Some code
    

    进一步,你需要检查实例是否被注入然后使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 2012-01-17
      • 1970-01-01
      • 2011-10-17
      • 2019-01-31
      • 2012-08-01
      • 1970-01-01
      相关资源
      最近更新 更多