Setter-Based Dependency Injection

Revision as of 03:31, 3 June 2018 by Rasimsen (talk | contribs) (Created page with "For setter-based DI, the container will call setter methods of our class, after invoking a no-argument constructor or no-argument static factory method to instantiate the bean...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

For setter-based DI, the container will call setter methods of our class, after invoking a no-argument constructor or no-argument static factory method to instantiate the bean. Let’s create this configuration using annotations:

@Bean
public Store store() {
    Store store = new Store();
    store.setItem(item1());
    return store;
}

We can also use XML for the same configuration of beans:

<bean id="store" class="org.baeldung.store.Store">
    <property name="item" ref="item1" />
</bean>

Constructor-based and setter-based types of injection can be combined for the same bean. The Spring documentation recommends using constructor-based injection for mandatory dependencies, and setter-based injection for optional ones.