Spring基於建構函式和設值函式的依賴注入

weixin_33797791發表於2017-08-29

通過建構函式就是B類在A類的建構函式裡初始化,標籤應該是<constructor-arg>。SpellChecker 類和SpellChecker1類在TextEditor的建構函式裡。

public class TextEditor {
    private SpellChecker spellChecker;
    private SpellChecker1 spellChecker1;

    public TextEditor(SpellChecker spellChecker, SpellChecker1 spellChecker1) {
        super();
        System.out.println("Inside TextEditor constructor.");
        this.spellChecker = spellChecker;
        this.spellChecker1 = spellChecker1;
    }

    public void spellCheck() {
        spellChecker.checkSpelling();
        spellChecker1.checkSpelling();
    }

}
<bean id="textEditor" class="com.spring.test1.TextEditor">
        <constructor-arg name="spellChecker" ref="spellChecker"></constructor-arg>
        <constructor-arg name="spellChecker1" ref="spellChecker1"></constructor-arg>
    </bean>

    <bean id="spellChecker" class="com.spring.test1.SpellChecker">
    </bean>
    <bean id="spellChecker1" class="com.spring.test1.SpellChecker1"></bean>

通過設值函式就是B類在A類的getter/setter方法裡初始化,標籤應該是<property>。IUser介面在PersonImpl的setiUser方法裡。

<bean id="iUser" class="com.tutorialspoint.impl.UserImpl"></bean>
    <bean id="iPerson" class="com.tutorialspoint.impl.PersonImpl">
        <property name="iUser" ref="iUser"></property>
    </bean>
public class PersonImpl implements IPerson {

    private IUser iUser;
    public IUser getiUser() {
        return iUser;
    }

    public void setiUser(IUser iUser) {
        this.iUser = iUser;
    }

    @Override
    public void play() {
        // TODO Auto-generated method stub
        System.out.println(getiUser().eat("屎屎屎"));
    }
}

相關文章