Groovyも1.0になったし、動的なクラス生成を使ってインターフェースレスにDIコンテナを使うのが、ナウなヤングにトレンディかも…と考えて、少し触ってみる。
依存するライブラリは次の通り。
public class Foo {
private Bar bar;
private Zoo zoo;
public Foo(Bar bar, Zoo zoo) { this.bar = bar; this.zoo = zoo; }
public void func() { System.out.println("Foo#func()"); bar.func(); zoo.func(); }
}
public class Bar {
private Baz baz;
public Bar(Baz baz) { this.baz = baz; }
public void func() { System.out.println("Bar#func()"); baz.func(); }
}
public class Zoo {
public void func() { System.out.println("Zoo#func()"); }
}
public class Baz {
public void func() { System.out.println("Baz#func()"); }
}
エントリクラス
public class Main {
public static void main(String[] args) {
try { Main main = new Main(); main.__main__(args); } catch (Exception e) { e.printStackTrace(); }
}
private void __main__(String[] args) throws Exception {
PicoContainer pico = buildContainer();
Foo foo = (Foo) pico.getComponentInstanceOfType(Foo.class);
foo.func();
}
private PicoContainer buildContainer() throws FileNotFoundException {
Reader script = new FileReader("nanocontainer.groovy");
GroovyContainerBuilder builder = new GroovyContainerBuilder(script, getClass().getClassLoader());
ObjectReference containerRef = new SimpleReference();
builder.buildContainer(containerRef, new SimpleReference(), null, true);
return (PicoContainer) containerRef.get();
}
}
Groovyスクリプト
import pico_nano.*
pico = builder.container(parent:parent) {
component(class:Foo)
component(class:Bar)
component(class:Zoo)
component(class:Baz)
}
実行結果
Foo#func()
Bar#func()
Baz#func()
Zoo#func()