com.google.inject.name.Names の bindProperties は楽であるが、
インジェクトされる側のコードは、
@Inject @Named(key)
を並べることになるので、インジェクトされる側のコードだけを読むと
他のバインドとの区別はしにくい。インジェクトされる側のコードだけを
眺めさせるようなプロジェクトでは不向きなのかも。
ならば、
@Inject @Property(key)
と書くようにできれば良い。
Property アノテーションを次のように作ったら、手始めは以外なところから。。。
-----------------------------------------------
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.google.inject.BindingAnnotation;
/**
* プロパティ値を約束するアノテーション
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@BindingAnnotation
public @interface Property{
String value();
}
----------------------------------------------
このアノテーションをスーパーインターフェ-スにしたクラスを
インナークラスとしてそのインスタンスを返すユーティリティを用意する。
import java.lang.annotation.Annotation;
import static com.google.inject.internal.Preconditions.checkNotNull;
/**
* Annotationを生成するメソッドを提供
*/
public final class PickProperty{
private PickProperty(){}
/**
* com.google.inject.binder.AnnotatedBindingBuilder.annotatedWith の引数として指定する
* @param key 属性Key
* @return PropertyをsuperインターフェースにとするAnnotationオブジェクト
*/
public static Annotation pointed(String key){
return new PropertyImpl(key);
}
static class PropertyImpl implements Property{
private String value;
PropertyImpl(String key){
this.value = checkNotNull(key,"@Property value NULL error");
}
@Override
public String value(){
return this.value;
}
/*
* @see java.lang.annotation.Annotation#annotationType()
*/
@Override
public Class<? extends Annotation> annotationType(){
return Property.class;
}
@Override
public boolean equals(Object obj){
if (!(obj instanceof Property)){
return false;
}
Property other = (Property)obj;
return this.value.equals(other.value());
}
@Override
public int hashCode() {
// This is specified in java.lang.Annotation.
return (127 * "value".hashCode()) ^ this.value.hashCode();
}
@Override
public String toString() {
return "@" + Property.class.getName() + "(value=" + this.value + ")";
}
}
}
-------------------------------------------------
このトリッキーに見えるアノテーションインスタンスを
生成することが、バインド定義で役にたつ。
今日はここまでにする。