liguofeng29’s blog

個人勉強用ブログだっす。

Dependency Injectionタイプその2 - セッター・インジェクション

セッターメソッドにDIを行なうのがセッター・インジェクションです。

コンポーネントのプロパティには、componentタグの子タグであるpropertyタグを使って指定します。

プロパティ名はname属性で指定します。

 

app.dicon
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE components PUBLIC "-//SEASAR//DTD S2Container 2.4//EN"
 
<components>
  <include path="convention.dicon"/>
  <include path="aop.dicon"/>
 
    <!-- コンポーネント定義 -->
    <component name="setterDI" class="SetterDI" instance="singleton">
      <property name="message">"これはセッターDI後のメッセージです。"</property>
    </component>
 
</components>

 

SetterDI.java
public class SetterDI  {
 
    private String message;
 
    public void setMessage(String message) {
        this.message = message;
    }
 
    // S2Container2.4.17からはセッターメソッドがなくてもpublicプロパティであればOK.
    public String getMessage() {
        return this.message;
    }
}

 

TestClass.java
import org.seasar.framework.container.SingletonS2Container;
import org.seasar.framework.container.factory.SingletonS2ContainerFactory;
 
public class TestClass {
 
    public static void main(String[] args) {
        // S2Container初期化
        SingletonS2ContainerFactory.init();
 
        // コンポーネント取得
        SetterDI setterDI = SingletonS2Container.getComponent("setterDI");
        System.out.println(setterDI.getMessage());
 
        // S2Container破棄
        SingletonS2ContainerFactory.destroy();
    }
}

 

出力メッセージ
これはセッターDI後のメッセージです。