DI方法
SpringでDIするには以下の方法があります。
・「@Autowired」を利用した実装
・「applicationContext.xml」を利用した実装
ここではXMLを利用した実装を紹介します。
applicationContext.xml
呼び出す側で利用するBeandIdを「b」とします。
メンバー変数の「price」に26000をインジェクションします。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cont ext="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www .springframework.org/schema/context/spring-context-4.1.xsd">
<bean id="b" class="ex.spring.practice.B_ServiceImpl">
<property name="c">
<bean class="ex.spring.practice.C_RepositoryImpl ">
<property name="price" value="26000" />
</bean>
</property>
</bean>
</beans>
メインクラス
「b」には「applicationContext.xml」で設定した「B_ServiceImpl」がインジェクションされます。
public class A_Client {
public static void main(String[] args) {
// Bean設定ファイルを指定してアプリケーションコンテキス ト(DIコンテナへの入り口)を得る
ApplicationContext context = new ClassPathXmlApplication Context(
"/META-INF/application-context.xml");
// DIコンテナより"b"という名前のBeanを取得する
// 実装クラスではなくインタフェースのB_Serviceしか記載は ない
B_Service b = (B_Service) context.getBean("b");
// 後は元の処理と同じ
long total = b.adjustment("PS4", 8);
System.out.println("合計:¥" + total);
}
}
ビジネスロジック
I/Fクラスは省略します。
「c」には「applicationContext.xml」で設定した「C_RepositoryImpl」がインジェクションされます。
public class B_ServiceImpl implements B_Service {
// DI対象
private C_Repository c;
// SpringがIDするのに必要なセッターを作成する
public void setC(C_Repository c) {
this.c = c;
}
@Override
public long adjustment(String lessonName, int number) {
System.out.println("PS:" + lessonName + " 台:" + number);
long price = c.checkPrice(lessonName);
return price * number;
}
}
リポジトリークラス
I/Fクラスは省略します。
「price」には「applicationContext.xml」で設定した「26000」がインジェクションされます。
public class C_RepositoryImpl implements C_Repository {
// 単価を表すフィールドを初期値
private long price;
// price用のセッター(値設定用のメソッド)
// SpringがDIする際に利用
public void setPrice(long price) {
this.price = price;
}
@Override
public long checkPrice(String lessonName) {
return price;
}
}