我試圖帶註釋的變量注入請求範圍:吉斯:在請求範圍不能注入註釋類型
Map<Key<?>, Object> seedMap = ImmutableMap.<Key<?>, Object>builder().
put(Key.get(String.class, Names.named("name")), name).build();
return ServletScopes.scopeRequest(new InjectingCallable<>(injector,
GetModule.class), seedMap).call();
其中,InjectingCallable注入GetModule請求範圍內:
/**
* A Callable that is constructed in one scope and injects a Callable into a potentially separate
* scope.
* <p/>
* @param <V> the type of object returned by the Callable
* @author Gili Tzabari
*/
public final class InjectingCallable<V> implements Callable<V>
{
private final Injector injector;
private final Class<? extends Callable<V>> delegate;
/**
* Creates a new InjectingCallable.
* <p/>
* @param injector the Guice injector
* @param delegate the class to inject and delegate to
*/
public InjectingCallable(Injector injector, Class<? extends Callable<V>> delegate)
{
Preconditions.checkNotNull(injector, "injector may not be null");
Preconditions.checkNotNull(delegate, "delegate may not be null");
this.injector = injector;
this.delegate = delegate;
}
@Override
public V call() throws Exception
{
return injector.getInstance(delegate).call();
}
}
GetModule定義如下:
@RequestScoped
private static class GetModule implements Callable<Module>
{
private final String name;
private final Session session;
@Inject
public GetModule(@Named("name") String name, Session session)
{
this.name = name;
this.session = session;
}
}
當我運行此代碼時,我得到這個呃ROR:
1) No implementation for java.lang.String annotated with @com.google.inject.name.Named(value=name) was bound.
while locating java.lang.String annotated with @com.google.inject.name.Named(value=name)
如果我同一個變量綁定到它的工作原理全局範圍。如果我刪除註釋,它會起作用。此問題似乎特定於請求範圍註釋變量。有任何想法嗎?
嘿,對於ImmutableMap的FYI,您不需要在等號右側的'builder()'調用中指定泛型,因爲您在左側具有泛型。這是靜態構建器()方法的重點。即''ImmutableMap,Object> seedMap = ImmutableMap.builder()。put(...)。build()'。 –
Tom
@Tom,我得到一個編譯器錯誤,如果我這樣做。在Java7更新2下,默認情況下,它將右側解析爲