2012-04-13 32 views
0

吉斯提供所謂綁定註釋,這似乎真正分解到接收機類和實例級別註釋的兩個變化:吉斯:講座或實例級綁定註釋

「類級」 :

bind(Service.class).annotatedWith(Red.class).to(RedServiceImpl.class); 

@Red 
public class SomeService implements Service { ... } 

Service redSvc = injector.getInstance(SomeService.class); 

「實例級」:

bind(Service.class).annotatedWith(Names.named("Blue").to(BlueServiceImpl.class); 
@Blue blueSvc = injector.getInstance(Service.class); 

當是一種方法優先比其他?看來,課堂級別的註釋比實例級別更加絕對/不靈活。兩種方法的優缺點/注意事項/陷阱?

回答

1

我不知道我理解你的問題。您使用綁定註釋是不規則的。您通常不會註釋局部變量或類,而是字段和參數。

您的第一個代碼示例導致注入器返回SomeService,但不是因爲您的註釋或綁定,而是因爲SomeService是具體實現。要是你問這個:

Service redSvc = injector.getInstance(Service.class); 

你會得到一個錯誤:

1) No implementation for com.example.Service was bound. 
    while locating com.example.Service 

你的第二個例子也是不正確的。如果您使用Names來定義綁定,則必須使用@Named來訪問該綁定。使用@Blue會導致編譯器錯誤。正確的用法是@Named(value="Blue")

的綁定批註常見的最佳做法是這樣的:

@BindingAnnotation 
@Target({ FIELD, PARAMETER, METHOD }) 
@Retention(RUNTIME) 
public @interface MyAnno 

在這種情況下,這兩個是編譯錯誤:

@Red // not allowed 
public class SomeService implements Service { ... } 

@Blue // not allowed 
blueSvc = injector.getInstance(Service.class); 
0

唯一真正的區別是,在一種情況下,您爲整個註釋綁定,而在另一種情況下,您使用特定參數綁定到註釋。並非所有註釋甚至都有參數,在這種情況下,與註釋類綁定是非常正常的。