Setter-Based Dependency Injection

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:

public Store store() {
    Store store = new Store();
    return store;

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

<bean id="store" class="">
    <property name="item" ref="item1" />

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.