Picoでセッター・インジェクション

Picoはシンプルでいいなー。jarは1個だけだし。


メイン。


package piconano;

import org.picocontainer.MutablePicoContainer;
import org.picocontainer.defaults.DefaultPicoContainer;
import org.picocontainer.defaults.SetterInjectionComponentAdapterFactory;

import piconano.component.Hoge;
import piconano.component.impl.BarImpl;
import piconano.component.impl.FooImpl;
import piconano.component.impl.HogeImpl;
import piconano.component.impl.ZooImpl;

public class Main {

public static void main(String[] args) {
MutablePicoContainer container = new DefaultPicoContainer(
new SetterInjectionComponentAdapterFactory());

container.registerComponentImplementation(ZooImpl.class);
container.registerComponentImplementation(BarImpl.class);
container.registerComponentImplementation(FooImpl.class);
container.registerComponentImplementation(HogeImpl.class);

Hoge hoge = (Hoge) container.getComponentInstanceOfType(Hoge.class);
hoge.perform();
}
}

コンポーネント(インターフェース)。


package piconano.component;

public interface Bar {

public void perform();

}


package piconano.component;

public interface Foo {

public void perform();

}


package piconano.component;

public interface Hoge {

public void perform();

}


package piconano.component;

public interface Zoo {

public void perform();

}

コンポーネント(実装)。


package piconano.component.impl;

import piconano.component.Bar;

public class BarImpl implements Bar {

public void perform() {
System.out.println(this);
}

}


package piconano.component.impl;

import piconano.component.Foo;
import piconano.component.Zoo;

public class FooImpl implements Foo {

private Zoo zoo = null;

public void setZoo(Zoo zoo) {
this.zoo = zoo;
}

/////////////////////////////////////////////////////////////////
public void perform() {
System.out.println(this);
zoo.perform();
}

}


package piconano.component.impl;

import piconano.component.Bar;
import piconano.component.Foo;
import piconano.component.Hoge;

public class HogeImpl implements Hoge {

private Foo foo = null;

public void setFoo(Foo foo) {
this.foo = foo;
}

private Bar bar = null;

public void setBar(Bar bar) {
this.bar = bar;
}

/////////////////////////////////////////////////////////////////
public void perform() {
System.out.println(this);
foo.perform();
bar.perform();
}

}


package piconano.component.impl;

import piconano.component.Zoo;

public class ZooImpl implements Zoo {

public void perform() {
System.out.println(this);
}

}