先日の続き、アノテーションをスーパーインターフェースにしたクラスの利用で、
いよいよ、バインドする手順。
aaa.proerties という属性ファイルに記述された属性をセットする
Google guice インジェクションである。
import java.util.Enumeration;
import java.util.ResourceBundle;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
:
Injector injector = Guice.createInjector(new AbstractModule(){
// aaa.propeties ファイルを読込む
ResourceBundle rs = ResourceBundle.getBundle("aaa");
@Override
protected void configure(){
for(Enumeration<String> en = this.rs.getKeys();en.hasMoreElements();){
String key = en.nextElement();
binder().bind(String.class)
.annotatedWith(PickProperty.pointed(key))
.toInstance(this.rs.getString(key));
}
}
}
);
Sample sample = injector.getInstance(Sample.class);
System.out.println(sample.getHostname());
System.out.println(sample.getOwner());
System.out.println(sample.getMax());
----------------------------------------
import com.google.inject.Inject;
public class Sample{
@Inject @Property("Hostname") private String hostname;
private String owner;
@Inject @Property("max") private int max;
public String getHostname(){
return this.hostname;
}
public String getOwner(){
return this.owner;
}
public int getMax(){
return this.max;
}
}