0

我正在使用 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. 如果没有,那么我该如何摆脱这个问题?
4

1 回答 1

2

根据您的配置,beanSportService基于.ServiceCondition

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

话虽如此,StudentProcessor不能有一个具体@Autowired的 for SportService

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

@Autiwired
private SportService sportService;
//Some code

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

此外,您需要检查实例是否被注入然后使用它。

于 2018-05-23T10:03:53.947 回答