【发布时间】:2019-03-27 19:10:55
【问题描述】:
假设我有这门课
class Foo implements IFoo { Foo() {} }
class Fooz implements IFoo { Fooz() {}}
class Foobar implement IFoobar {
@Autowired
Foobar (Foo foo) {}
}
class Foobarz implement IFoobar {
@Autowired
Foobarz (Bar bar) {}
}
在简单的情况下,我可以解决我的问题:
class Bar {
@Autowired
Bar (IFoo foo) {
this.foo = foo;
}
}
但是,如果我希望能够根据我的配置文件选择我的 IFoo 和 IFoobar 实例,我需要这样做:
@Configuration
class Configuration {
@Bean
foo () {
return this.isZ() ? new Fooz() : new Foo ();
}
@Bean
foobar () {
return this.isZ() ? new Foobarz(/* ??????? */) : new Foobar (/* ??????? */);
}
}
如您所见,我无法实例化我的 Foobar,因为我需要另一个 bean。我知道有 ApplicationContext.getBean,但我不能确定当 foobar() 被调用时它是否会在我的 Configuration 类中被初始化。
而且我也不想调用this.foo(),因为那样会创建对象的另一个引用,而且我不确定执行和初始化的顺序
【问题讨论】:
-
您目前使用的是什么版本的 Spring? 4+?
-
我使用的是 5.0.9
-
可以将参数传递给
@Bean方法,也可以从@Bean方法调用其他@Bean方法。 -
另请参阅
@Conditional或@Profile以决定使用哪个实现。