CDI Injection in Hibernate Entities

前端 未结 3 1734
小蘑菇
小蘑菇 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: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

提交回复
热议问题