【发布时间】:2012-01-23 19:34:18
【问题描述】:
我正在尝试将带注释的变量注入 REQUEST 范围:
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 在 REQUEST 范围内注入 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;
}
}
当我运行这段代码时,我得到了这个错误:
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,您不需要在等号右侧的
builder()调用中指定泛型,因为您在左侧有泛型。这就是静态 builder() 方法的重点。即 -ImmutableMap<Key<?>, Object> seedMap = ImmutableMap.builder().put(...).build(). -
@Tom,如果我这样做,我会收到编译器错误。在 Java7 更新 2 下,它默认将右侧解析为