如何在Spring中使用@Conditional注解有条件地解决Bean依赖关系

huangapple go评论91阅读模式
英文:

How to resolve bean dependencies conditionally in Spring using @Conditional annotation

问题

我有一个bean,它还依赖于另一个bean,这两个bean都使用相同的Spring条件注释进行了注释:

@Component
@Conditional(ImportEnabledCondition.class)
public class ImportEntityResource {

@Autowired
ImportService importService;
....
}

importService:

@Component
@Conditional(ImportEnabledCondition.class)
public class ImportService {...}

但我总是收到org.springframework.beans.factory.NoSuchBeanDefinitionException异常。
我将不胜感激地接受有关如何解决此问题的任何指示。

英文:

I have a bean which also has a dependency on another bean, both of which are annotated with the same spring conditional:

@Component
@Conditional(ImportEnabledCondition.class)
public class ImportEntityResource {

@Autowired
ImportService importService;
....
}

The importService:

@Component
@Conditional(ImportEnabledCondition.class)
public class ImportService{...}

but I always get the org.springframework.beans.factory.NoSuchBeanDefinitionException exception.
I'd appreciate any pointers as to how to resolve this issue.

答案1

得分: 1

@Conditional 用于根据一些条件在 Spring 上下文中注册 bean。在您的情况下,您可以将其移除,因为 Spring 将会将依赖视为 ImportEntityResource 具有 ImportService 作为成员。如果依赖关系不够明确,您可以使用 @DependsOn。

英文:

@Conditional is used to register bean in Spring context depending of some conditions. In your case, you can just remove it as Spring will see the dependency as ImportEntityResource has ImportService as member. If the dependency is less explicit you can use @DependsOn.

huangapple
  • 本文由 发表于 2020年8月7日 22:16:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63303637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定