ApplicationBinder 中泛型的 JAX-RS Bind 实现
JAX-RS Bind implementation of generic type in ApplicationBinder
是否可以在 AbstractBinder 的实现中将 class 与类型参数绑定?
通用存储库class
public class Repository<T>{ ... }
服务class
public class AccountService{
Repository<User> repository;
@Inject
public AccountService(Repository<User> repository){
this.repository = repository;
}
}
在活页夹中绑定通用存储库
public class ApplicationBinder extends AbstractBinder {
@Override
protected void configure() {
bind(Repository<User,Long>).to(Repository<User,Long>.class); <=== not working!
}
您可以使用TypeLiteral
Supports inline instantiation of objects that represent parameterized types with actual type parameters. An object that represents any parameterized type may be obtained by subclassing TypeLiteral
.
TypeLiteral<List<String>> stringListType = new TypeLiteral<List<String>>() {};
而不是 bind
,您需要使用 bindAsContract(TypeLiteral)
,因为没有 bind
方法接受 TypeLiteral
[1].
bindAsContract(new TypeLiteral<Repository<User, Long>>(){});
[1] - 在 AbstractBinder
文档中查看更多信息。
是否可以在 AbstractBinder 的实现中将 class 与类型参数绑定?
通用存储库class
public class Repository<T>{ ... }
服务class
public class AccountService{
Repository<User> repository;
@Inject
public AccountService(Repository<User> repository){
this.repository = repository;
}
}
在活页夹中绑定通用存储库
public class ApplicationBinder extends AbstractBinder {
@Override
protected void configure() {
bind(Repository<User,Long>).to(Repository<User,Long>.class); <=== not working!
}
您可以使用TypeLiteral
Supports inline instantiation of objects that represent parameterized types with actual type parameters. An object that represents any parameterized type may be obtained by subclassing
TypeLiteral
.TypeLiteral<List<String>> stringListType = new TypeLiteral<List<String>>() {};
而不是 bind
,您需要使用 bindAsContract(TypeLiteral)
,因为没有 bind
方法接受 TypeLiteral
[1].
bindAsContract(new TypeLiteral<Repository<User, Long>>(){});
[1] - 在 AbstractBinder
文档中查看更多信息。