简体   繁体   English

使用条件Bean自动装配构造函数

[英]Autowiring Constructor With Conditional Beans

In a @Service , I want to include two @Component , say ComponentA and ComponentB . @Service ,我想包含两个@Component ,例如ComponentAComponentB

Both of these components are conditional on some property (eg some environment variable; meaning these beans do not exist if those environment variables are not set). 这两个组件都取决于某个属性(例如,某个环境变量;这意味着如果未设置这些环境变量,则这些bean不存在)。

In the service, there are other auto wired beans, which are not optional. 在该服务中,还有其他自动有线bean,这不是可选的。 Given that I am using constructor dependency injection, I do not want to create multiple constructors, but indicate to Spring to use null when instantiating my service. 鉴于我正在使用构造函数依赖项注入,因此我不想创建多个构造函数,而是指示Spring在实例化我的服务时使用null The following works: 以下作品:

public MainService(NonOptionalBean1 b1, NonOptionalBean2 b2,
                   ..., ComponentA a, ComponentB b) { ... }
public MainService(NonOptionalBean1 b1, NonOptionalBean2 b2,
                   ..., ComponentA a) { ... }
public MainService(NonOptionalBean1 b1, NonOptionalBean2 b2,
                   ..., ComponentB b) { ... }
public MainService(NonOptionalBean1 b1, NonOptionalBean2 b2,
                   ...) { ... }

But this requires the creation of four constructors depending on how many conditional beans are present (both, none, exactly one). 但这需要创建四个构造函数,具体取决于存在多少条件Bean(两者都不是,确切地说是一个)。 This works, but in the general case requires an exponential number of constructors - I can only assume there is a better way. 这行得通,但是通常情况下需要成倍数量的构造函数-我只能假设有更好的方法。

Given the drawbacks of field injection, and my desire to keep my injected beans final , I am hoping to do better than using setter-injection or field-injection. 考虑到田间注射的弊端,以及我希望使注射的豆子保持final愿望,我希望比使用setter-injection或field-injection做得更好。 Perhaps, something that looks like... 也许,看起来像...

public MainService(NonOptionalBean1 b1, NonOptionalBean2 b2,
                   ..., @Optional ComponentA a, @Optional ComponentB b) { ... }

You can use Optional<YourOptionalBean> with Spring. 您可以将Optional<YourOptionalBean>与Spring一起使用。 It works with constructor injection. 它与构造函数注入一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM