问题描述:

In XML context based bean configuration file, if I want to refer a bean as property, I would use:

<bean class="com.example.Example" id="someId">

<property name="someProp" refer="anotherBean"/>

</bean>

<bean class="com.example.AnotherBean" id="anotherBean">

</bean>

So the Example bean will use the anotherBean as its property

So in the concept of annotation-based configuration java file:

@Configuration

class GlobalConfiguration {

@Bean

public Example createExample(){

return;

//here how should I refer to the bean below?

}

@Bean

public AnotherBean createAnotherBean(){

return new AnotherBean();

}

}

网友答案:

Here is a first solution, where you have both bean definitions in one @Configuration class.

@Configuration
class GlobalConfiguration {
    @Bean
    public Example createExample(){
        final Example example = new Example();
        example.setSomeProp(createAnotherBean());
        return example;
    }

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

Second possibility is to use autowiring like below:

 @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();
        }
    }

Third possibility is to split those declarations among two different @Configuration classes and use autowiring.

@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;
    }
 }
相关阅读:
Top