【问题标题】:CDI producer method for data model数据模型的 CDI 生产者方法
【发布时间】:2011-07-22 17:26:04
【问题描述】:

我希望能够@Inject 支持 RichFaces 4 ExtendedDataTable 的数据模型,但它需要 EntityManager 来完成它的工作。当然,EntityManager 的查询需要知道 Class,我宁愿不将其传递给方法调用(在这种情况下,我的代码不会调用方法);理想情况下,它会在构造函数中。

类似这样的:

public class DataModel<T> {
    @Inject private EntityManager em;
    private Class<T> entityClass;

    public DataModel(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    //Sample method - this class will handle much more complex queries
    public T findEntity(String key) {
        return em.find(entityClass, key);
    }

是否可以创建一个 CDI @Producer 用于将此 DataModel 注入到我的支持 bean 中?我已经考虑过制作一个预选赛,这样你就可以做类似的事情

@Inject @JType(value = MyEntity.class) DataModel<MyEntity> dataModel;

但这似乎很笨拙,并且还需要我的@Producer 调用new() - 我认为这不允许将EntityManager 注入DataModel。此外,我不确定您将如何要求开发人员添加限定符。

或者也许有更好的方法来解决这个问题,而我错过了什么?

【问题讨论】:

  • 我会按照你的直觉行事。过度应用设计模式和框架并不是好的设计,它们是交流的工具。

标签: java java-ee-6 cdi


【解决方案1】:

我使用 seam3 中的 seam-persistence 模块执行此操作。 :

制作人:

public class EntityManagerProducer {

   @Produces
   @ExtensionManaged
   @ConversationScoped
   @PersistenceUnit(unitName = "yourUnitName")
   private EntityManagerFactory emf;
}

然后你可以@Inject 实体管理器。

否则,DeltaSpike 项目似乎很有前途(从未使用过)

【讨论】:

  • 感谢您的回复!已经一年了,我已经着手进行其他项目,所以我无法验证这是否能解决问题,但我怀疑是这样。
猜你喜欢
  • 2015-10-01
  • 2011-11-20
  • 2023-03-29
  • 2012-06-10
  • 2017-09-25
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 2022-10-12
相关资源
最近更新 更多