Search code examples
javaspringjava-ee-6

Spring dependency injection using setter method?


I have below classes.

public class SomeBeanClass implements SomeInterface{


    private IAccountHistory acctHistory;

    public void setAccountHistory(IAccountHistory  acctHistory) {
        this.acctHistory = acctHistory;
    }

}


public interface IAccountHistory{
 //some methods
}

public class AccountHistory implements IAccountHistory{
  //some logic
}

Spring configuration:

<bean name="someBean" class="com.mypack.SomeBeanClass">
        <property name="AccountHistory">
            <bean class="com.mypack.AccountHistory"/>
        </property>
</bean>

In above spring configuration, property name is AccountHistory . But SomeBeanClass does not have any property named AccountHistory. How is injection working here? Please help me.


Solution

  • But SomeBeanClass does not have any property named AccountHistory.

    It does, right here:

    public void setAccountHistory(IAccountHistory  acctHistory) {
        this.acctHistory = acctHistory;
    }
    

    A property isn't a field. It is a Java bean property (with a few extra naming allowances) represented with a getter or setter.