[英]How to @Inject object with generic type
我正在我們公司的項目中工作,但是注入對象時遇到問題。 考慮一下我有這個實體提供者:
@Stateless
@TransactionManagement
public class EntityProviderBean<T> extends CachingMutableLocalEntityProvider<T> {
public EntityProviderBean(Class<T> entityClass) {
super(entityClass);
setTransactionsHandledByProvider(false);
}
@PersistenceContext(unitName = CoreApplication.PERSISTENCE_UNIT)
private EntityManager em;
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
protected void runInTransaction(Runnable operation) {
super.runInTransaction(operation);
}
@PostConstruct
public void init() {
setEntityManager(em);
setEntitiesDetached(false);
}
}
和擴展的JPAContainer使用上面的實體提供者
@UIScoped
public class IncidentContainer extends JPAContainer<Incident> {
private static final long serialVersionUID = 8360570718602579751L;
@Inject
EntityProviderBean<Incident> provider;
public IncidentContainer() {
super(Incident.class);
}
@PostConstruct
protected void init() {
setEntityProvider(provider);
}
}
問題是(而且我理解)我無法使用類類型定義@Inject對象,因為inject方法需要空白構造函數。 這是某種解決方案如何使其起作用? 現在我越來越異常
org.apache.webbeans.util.InjectionExceptionUtils.throwUnsatisfiedResolutionException(InjectionExceptionUtils.java:77)
非常感謝您的回答:) Ondrej
AFAIK Bean需要一個沒有自變量的構造函數,否則所有構造函數的參數也必須被注入。 您將無法滿足這些要求。
當CDI容器實例化bean類時,它將調用CDI bean的bean構造函數。
CDI查找默認的bean構造函數,或者使用@Inject注釋以獲取bean的實例。
bean構造函數注入的一個優點是,它允許bean不可變。
您遇到的問題是
IncidentContainer bean類沒有任何默認構造函數,也沒有使用@Injection注釋的構造函數。
您可以設置如下
public class IncidentContainer extends JPAContainer<Incident> {
// @Inject no need to do filed injection here
private EntityProviderBean<Incident> provider;
@Inject // add this one
public IncidentContainer(EntityProviderBean<Incident> provider) {
super(Incident.class);
this.provider = provider;
}
@PostConstruct
protected void init() {
setEntityProvider(provider);
}
}
EntityProviderBean bean類沒有任何默認構造函數,也沒有使用@Injection注釋的構造函數。
您可以設置如下
public class EntityProviderBean<T> extends CachingMutableLocalEntityProvider<T> {
public EntityProviderBean(Class<T> entityClass) {
super(entityClass);
setTransactionsHandledByProvider(false);
}
// add this cdi bean construtor
@Inject
public EntityProviderBean(Incident incident) {
this((Class<T>) incident.getClass());
}
protected void runInTransaction(String operation) {
super.runInTransaction(operation);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.