Difference between revisions of "Setter-Based Dependency Injection"
(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...") |
(No difference)
|
Latest revision as of 03:31, 3 June 2018
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.