Java 如何在基于注释的配置文件中将另一个bean作为属性引用
在基于XML上下文的bean配置文件中,如果我想将bean引用为属性,我将使用:Java 如何在基于注释的配置文件中将另一个bean作为属性引用,java,spring,Java,Spring,在基于XML上下文的bean配置文件中,如果我想将bean引用为属性,我将使用: <bean class="com.example.Example" id="someId"> <property name="someProp" refer="anotherBean"/> </bean> <bean class="com.example.AnotherBean" id="anotherBean"> </bean> 这里是第一个解
<bean class="com.example.Example" id="someId">
<property name="someProp" refer="anotherBean"/>
</bean>
<bean class="com.example.AnotherBean" id="anotherBean">
</bean>
这里是第一个解决方案,在一个
@Configuration
类中有两个bean定义
@Configuration
class GlobalConfiguration {
@Bean
public Example createExample(){
final Example example = new Example();
example.setSomeProp(createAnotherBean());
return example;
}
@Bean
public AnotherBean createAnotherBean(){
return new AnotherBean();
}
}
第二种可能是使用如下自动布线:
@Configuration
class GlobalConfiguration {
@Bean
@Autowired
public Example createExample(AnotherBean anotherBean){
final Example example = new Example();
example.setSomeProp(anotherBean);
return example;
}
@Bean
public AnotherBean createAnotherBean(){
return new AnotherBean();
}
}
第三种可能是在两个不同的@Configuration
类中拆分这些声明,并使用自动连接
@Configuration
class FirstConfiguration {
@Bean
public AnotherBean createAnotherBean(){
return new AnotherBean();
}
}
@Configuration
class SecondConfiguration {
@Autowired
private AnotherBean anotherBean;
@Bean
public Example createExample(){
final Example example = new Example();
example.setSomeProp(anotherBean);
return example;
}
}
对于未来遇到这个问题的人,这里有另一种方法 您可以将一个bean作为参数传递给另一个bean的工厂函数:
@Configuration
class Configuration {
@Bean
public AnotherBean createAnotherBean() {
return new AnotherBean();
}
@Bean
public Example createExample(AnotherBean anotherBean) {
var example = new Expample();
example.setSomeProp(anotherBean);
return example;
}
}
如果可能的话,您还可以在示例bean类定义中添加
@Autowired
注释(可能带有@Qualifier
),并跳过bean实例化中的setter。谢谢@JeremyGrand,我只检查了您提出的第二个解决方案,因为它整洁美观。这是第二个解决方案,谢谢。
@Configuration
class Configuration {
@Bean
public AnotherBean createAnotherBean() {
return new AnotherBean();
}
@Bean
public Example createExample(AnotherBean anotherBean) {
var example = new Expample();
example.setSomeProp(anotherBean);
return example;
}
}