cinqS
cinqS

Reputation: 1223

How to refer to another bean as a property in annotation-based configuration file

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

Upvotes: 11

Views: 15763

Answers (2)

Apurva Singh
Apurva Singh

Reputation: 5010

Just do:

@Configuration 
class GlobalConfiguration {

    @Bean
    public Example createExample(@Autowired AnotherBean anotherBean){
        //use another bean
        return new Example(anotherBean);
    }

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

Upvotes: 1

bart.s
bart.s

Reputation: 688

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;
    }
 }

Upvotes: 22

Related Questions