Translate

2012年7月31日火曜日

ちょっと複雑なDIを定義したGoogle Guiceサンプルを読む




複雑な構造をGoogle Guiceで
実現すると
どうもソースコードの可読性が下がるみたいだ。

Google GuiceのFAQのリンクに
サンプルコードのリンクがある。

http://pastie.org/368348


Carクラスにengine、transmission、drivelineというフィールドがあり
Google GuiceでDIする際に
transmissionがAutomaticTransmissionの(blue)Carインスタンスと
transmissionがManualTransmissionの(red)Carインスタンスを
出し分けるというものだ。


..これは
アノテーション定義しているけど
アノテーションとしては使用しないで
Guice#getInstance()でのblue/redの使い分けだけのために定義して
いるんだ。

で、各Car固有のインジェクトになるtransmissionは
2つのPrivateModuleをつくって
それぞれ中でアノテーションクラスでexpose()させて
Guice#getInstance()で指定できるようにしているのか..


でもこれだと
Springのほうが簡単でないのかな..

Spring beans configurationファイルは
以下の様な感じで書いて..

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="blue" class="sample.Car">
<property name="engine" ref="dieselEngine"></property>
<property name="transmission" ref="automaticTransmission"></property>
<property name="driveline" ref="frontWheelDrive"></property>
</bean>

<bean id="red" class="sample.Car">
<property name="engine" ref="dieselEngine"></property>
<property name="transmission" ref="manualTransmission"></property>
<property name="driveline" ref="frontWheelDrive"></property>
</bean>

<bean id="dieselEngine" class="sample.DieselEngine"></bean>

<bean id="automaticTransmission"
class="sample.AutomaticTransmission">
</bean>
<bean id="manualTransmission"
class="sample.ManualTransmission"></bean>

<bean id="frontWheelDrive" class="sample.FrontWheelDrive"></bean>

</beans>



呼び出す側は

package sample;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SampleMain {

public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("car.xml");

Car blueCar = (Car) context.getBean("blue");
System.out.println("Blue car transmission: " + blueCar.getTransmission());

Car redCar = (Car) context.getBean("red");
System.out.println("Red car transmission: " + redCar.getTransmission());
}

}

って感じで書けばいいだけだよなあ..

まあ確かにXMLが複雑になるっていう問題はあるけど。


それなりの規模の開発だったら
複雑なDI設定は
人的ミス減らすため
マクロとかEclipseプラグインとかツールをつくって
ツール経由で生成するとかになるけど
GuiceのModuleクラス生成よりは
XMLのほうが生成しやすいしなあ..



なるほど
Guice、あんまりはやってないわけだ..



そういえば..
マトリョーシカのような
自分と同じインスタンスを子供に持つ場合とか
商品によっては2段、3段と替えて売りたい場合とか
Guiceだったらどうするんだろう..

0 件のコメント:

既存アプリケーションをK8s上でコンテナ化して動かす場合の設計注意事項メモ

既存アプリをK8sなどのコンテナにして動かすには、どこを注意すればいいか..ちょっと調べたときの注意事項をメモにした。   1. The Twelve Factors (日本語訳からの転記) コードベース   バージョン管理されている1つのコードベースと複数のデプロイ 依存関係 ...