CDI Injection in Hibernate Entities

前端 未结 3 1735
小蘑菇
小蘑菇 2021-01-20 05:36

We are using CDI(JSR 299) in our application (JSF2/Seam3.0/Hibernate 3.5.6/GlassFish 3.1.1)

While we are unable to inject resources(Helper POJOs) in our managed bean

相关标签:
3条回答
  • 2021-01-20 06:05

    I don't really know CDI but i really don't think it is possible. Event if we could, in many cases, it would probably lead to a really bad design.

    Do you wish CDI to create a single hibernate entity for the whole application, and inject your helpers/services/whatever in it? Or do you wish CDI to inject stuff in any entity you create with "new Entity()"?


    Edit: Generally a Date Time utils doesn't hold any state and doesn't need any CDI injected stuff, so why not make all the methods static like what we find in apache commons DateUtils?

    If your Date Time utils need a state, make it a singleton (but take care with concurrency issues).

    If your Date Time utils needs to call other CDI beans (so it can't be static) then you'd rather make it a singleton, and inject on the singleton the other CDI beans.

    But it's a bad idea. This may lead to have a business layer that manage entities that call back the business layer or something like that, with some circular dependency problems and a tight coupling between your entities and your business layer.

    0 讨论(0)
  • 2021-01-20 06:07

    you can firing CDI Events in a JPA Entity or EntityListener. and inject the TestClass to the class which contains Observes method. look at following link for more information: http://blogs.bytecode.com.au/glen/2014/01/09/firing-cdi-events-from-a-jpa-entitylistener.html

    you can also access to the BeanManager as follow( instead JNDI lookup)

    CDI.Current().getBeanManager()

    0 讨论(0)
  • 2021-01-20 06:32

    It's a bad practice to systematically use JPA entity as CDI bean (but it's possible if you want to). That's mainly because of the 'C' of CDI : Context.

    All CDI implementations use proxy mechanism to handle injection of a bean of a given scope in a bean of a different scope. And as most JPA implementation use also proxy to handle some mechanism (Lazy Loading for instance) you will finished with a bunch of proxies in your class with different life cycles : a mess !

    Weld documentation as even a waning about this issue : Chapter 5. Scopes and Contexts

    However it could be useful in some case to expose an entity as CDI bean, but you'd prefer to use a producer to do so :

    @Produces
    @Named
    @RequestScoped
    private MyEntity produceMyEntity()
    {
         return new MyEntity(); //or any JPA lookup you'll need
    }
    

    This way is the most convenient but you should be very careful when mixing managed entities and CDI

    0 讨论(0)
提交回复
热议问题