Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

spring

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();
    }
}
like image 353
cinqS Avatar asked Feb 22 '17 09:02

cinqS


People also ask

Which annotation in the bean class indicates that the specified bean property?

C - This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring.

Which annotation is used to inject property values into beans?

A lesser known nugget of information is that you can also use the @Value annotation to inject values from a property file into a bean's attributes.

Which annotation is used to specify the bean with name?

We can also use the @Qualifier annotation to name the bean.


1 Answers

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;
    }
 }
like image 143
bart.s Avatar answered Oct 19 '22 06:10

bart.s