如何在基于注释的配置文件中将另一个bean称为属性

时间:2017-02-22 09:04:00

标签: 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>

因此Example bean将使用anotherBean作为其属性

所以在基于注释的配置java文件的概念中:

@Configuration
class GlobalConfiguration {
    @Bean
    public Example createExample(){
        return;
        //here how should I refer to the bean below?
    }

    @Bean
    public AnotherBean createAnotherBean(){
        return new AnotherBean();
    }
}

2 个答案:

答案 0 :(得分:10)

这是第一个解决方案,您可以在一个RepoB类中同时拥有两个bean定义。

@Configuration

第二种可能性是使用如下所示的自动装配:

@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

答案 1 :(得分:0)

对于未来遇到这个问题的人,这是另一种方法。

您可以将一个 bean 作为参数传递给另一个 bean 的工厂函数:

$ npm run env | grep npm_package_version | cut -d '=' -f 2