我正在开发一个基于JAX-RS的Java应用程序,使用Google Guice进行依赖注入。我的代码中有以下界面:
public interface LockProvider<L extends Lock> {
Optional<L> acquireLock(String lockId);
void releaseLock(L lock);
}
在上面的界面中,Lock是一个定义如下的接口:
public interface Lock {
String getLockId();
}
锁定界面由以下类实现:
public class DynamoDBLock implements Lock {
private final String lockId;
private final LockItem underLyingLock;
public DynamoDBLock(final String lockId, final LockItem underLyingLock) {
this.lockId = lockId;
this.underLyingLock = underLyingLock;
}
@Override
public String getLockId() {
return lockId;
}
public LockItem getUnderlyingLock() {
return underlyingLock;
}
}
LockProvider接口由以下类实现:
public class DynamoDBLockProvider implements LockProvider<DynamoDBLock> {
Optional<DynamoDBLock> acquireLock(String lockId) {
//implementation here
}
void releaseLock(DynamoDBLock lock) {
LockItem underlyingLockItem = lock.getUnderlyingLockItem();
//do something with underlyingLockItem
}
}
除了LockProvider之外,我不希望我的应用程序中的类知道underLying锁定项,这就是为什么我还没有在Lock界面中包含getUnderlyingLockItem。
现在,当我尝试将LockProvider绑定到DynamoDBLockProvider时,如下所示:
bind(new TypeLiteral<LockProvider<Lock>>() {}).to(DynamoDBLockProvider.class);
我在Eclipse中遇到以下编译错误:
The method to(Class<? extends LockProvider<Lock>>) in the type LinkedBindingBuilder<LockProvider<Lock>> is not applicable for the arguments (Class<DynamoDBLockProvider>)
据我所知,DynamoDBLockProvider&lt; DynamoDBLock&gt;不是LockProvider&lt; Lock&gt;的子类。是否有可能完成我想要做的事情,即将LockProvider绑定到DynamoDBLockProvider(以干净有效的方式)?
答案 0 :(得分:2)
DynamoDBLockProvider
的{{1}}个实例 <{1}}的实例。但他们是 LockProvider<Lock>
的实例。
一个并行示例是LockProvider<? extends Lock>
不的ArrayList<Integer>
个实例, List<Number>
个List<? extends Number>
个实例{ {3}}
将其应用于Guice,您将获得完全相同的编译失败。假设你有这样一个类:
public class IntegerList extends ArrayList<Integer> {}
然后像这样绑定它不会起作用:
binder.bind(new TypeLiteral<List<Number>>() {}).to(IntegerList.class); //won't compile
是否有可能完成我想要做的事情,即将LockProvider绑定到DynamoDBLockProvider(以干净有效的方式)?
以下绑定将起作用:
binder.bind(new TypeLiteral<LockProvider<? extends Lock>>() {}).to(DynamoDBLockProvider.class);