Java spring如何在不传递参数的情况下实例化@Autowired构造函数
假设我有这门课Java spring如何在不传递参数的情况下实例化@Autowired构造函数,java,spring,Java,Spring,假设我有这门课 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 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时它是否会在我的配置类中初始化
我也不想调用this.foo,因为那样会创建对象的另一个引用,而且我不确定执行和初始化的顺序。在您的情况下,下面的操作应该可以做到这一点
@Configuration
class Configuration {
@Bean
IFoo foo() {
return this.isZ() ? new Fooz() : new Foo ();
}
@Bean
IFoobar foobar(IFoo foo) { // IFoo bean declared above will be injected here by Spring
return this.isZ() ? new Foobarz(foo) : new Foobar(foo);
}
}
更新
但更优雅的方法是将@Service或@Component注释放在类上,@Bean声明应该从配置中删除
package com.foobarpkg.maybeanotherpkg;
@Service
class Foobar implement IFoobar {
@Autowired
Foobar (IFoo foo) { // not that interface should be used here instead of concrete class (Foo/Fooz)
}
}
。。。并让Spring知道其软件包位于
@Configuration
@ComponentScan(basePackages = {"com.foobarpkg"})
class Configuration {
@Bean
IFoo foo() {
return this.isZ() ? new Fooz() : new Foo ();
}
// foobar bean is no longer declared here
}
您当前使用的是哪个版本的Spring?4+?我使用的是5.0.9。你可以将参数传递给@Bean方法,你可以从@Bean方法调用其他@Bean方法。可能重复的请参阅@Conditional或@Profile来决定使用哪个实现。这看起来就是我想要的,尽管这不是最佳答案,无论如何,谢谢!