【问题标题】:How do I inject CDI beans into custom entity classes?如何将 CDI bean 注入自定义实体类?
【发布时间】:2014-12-13 11:47:29
【问题描述】:

我们使用 Cassandra(和 DataStax 驱动程序)来存储我们的实体。因此,我们有一个自定义实体服务,它在从 Cassandra 检索数据时创建实体类的新实例。

我还需要使用 CDI 将服务注入到我的实体类中。我该怎么做呢?当我只是在@Inject 注释处,它永远不会被注入。

public class Customer{

    @Inject
    private Event<DeactivationEvent> events;

    private String uid;

    public void setUid(String uid){
        this.uid = uid;
    }

    public String getUid(){
        return this.uid;
    }

    public void deactivate(){

        events.fire( new DeactivationEvent() );

    }

}


public CassandraEntityService{

    public static Customer findCustomer(String uid){

        ...whatever lookup logic...
        Customer customer = new Customer();

        customer.setUid(..)
        customer.set...

        return customer;

    }

}

作为参考,我使用的是 JBoss/Wildfly 8.1。

【问题讨论】:

    标签: jakarta-ee jboss cdi wildfly


    【解决方案1】:

    CassandraEntityService.findCustomer() 中的直接问题是 Customer 实例不是 CDI bean,因为 findCustomer 直接调用构造函数。

    使用entities as CDI beans 可能会遇到麻烦,但我认为(a)您需要Customer 的生产者方法,并且(b)CassandraEntityService 本身需要是另一个@Injects @ 987654329@,而不是直接调用构造函数。

    但是,对于更一般的问题(在实体更改时触发事件)的更好解决方案可能是 Entity Listener,在这种情况下,Customer 可能不需要成为 CDI bean。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 2019-08-04
      • 2013-09-01
      • 2023-03-10
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多