1 Reply Latest reply on Oct 19, 2014 5:29 PM by kwintesencja

    How do I inject CDI beans into Custom Entity Classes?

    firepod

      We use Cassandra (and the DataStax driver) to store our entities. As such we have a custom entity service that creates new instances of our entity classes when it retrieves data from Cassandra.

       

      I also need to inject services into my entity classes using CDI. How do I do this? When I simply at the @Inject annotation, it never gets injected.

       

      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 Customer findCustomer(String uid){
      
              ...whatever lookup logic...
              Customer customer = new Customer();
          
              customer.setUid(..)
              customer.set...
          
              return customer;
      
          }
      
      }
      

       

      For reference, I'm using JBoss/Wildfly 8.1.

       

      Thanks!

        • 1. Re: How do I inject CDI beans into Custom Entity Classes?
          kwintesencja

          Hi there, your problem is that you create the entity via new operator so CDI is not managing your entity...i can see two options:

           

          1. @Inject the Custumer so CDI can manage it which i think is not what you want
          2. or you can fire the event programactly like below:
          public void deactivate(){ 
                 BeanManager bm =  CDI.current().getBeanManager();
                 bm.fireEvent( new DeactivationEvent() ); 
              }
          
          

           

          if you use CDI 1.0 you have to lookup BeanManager via jndi, something like:

           

            

          BeanManager bm =  return (BeanManager) InitialContext.doLookup("java:comp/BeanManager");

           

           

          I hope it helps.