Why can't I inject 2 EJB's into 2 different managed beans that inject each other?

蹲街弑〆低调 提交于 2019-12-24 04:34:05

问题


ContactsBean

   @Named(value = "contactsBean")
@SessionScoped
public class ContactsBean implements Serializable {

    @EJB
    ContactsFacade contactsEJB;
    private List<Contacts> contacts = new ArrayList<Contacts>();
    @Inject
    DetailsBean detailsBean;

Details Bean

    @Named(value = "detailsBean")
@RequestScoped
public class DetailsBean {

    @EJB
    ContactsFacade contactsEJB;
    private Contacts detailsContact = new Contacts();

I can't do this. Whenever I called the EJB in details bean it throws EJB exception and this.

Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'

Any ideas guys? Thanks

**UPDATE**

Ok so I found out it seems that using a requestScoped bean is causing this problem. Why is this?


回答1:


Injection takes place directly after the construction of the bean. A session scoped bean is constructed only once per session. The session scope is broader than the request scope. There can be multiple requests inside one session. The injector wouldn't know which request scoped one it has to inject when there are multiple requests at the moment. There may even be no request at all.

To inject the one in the other, the acceptor has to be of the same or a more narrow scope than the injected object. Injecting a session scoped bean in a request scoped bean will just work. I'd suggest that you take this route instead.


Unrelated to the concrete problem, I'd also suggest to rethink the EJB approach as well. Do you really need to put the same @EJB on two beans which are aware about each other already? I'd suggest to remove the ContactsFacade from the DetailsBean and just let the DetailsBean delegate the job to the ContactsBean.




回答2:


ContactsBean is session-scoped, DetailsBean is request-scoped. You can't inject a request-scope bean into a session-scoped bean.

Similarly you can't inject a session-scoped bean into a application-scoped, and so on.



来源:https://stackoverflow.com/questions/4964180/why-cant-i-inject-2-ejbs-into-2-different-managed-beans-that-inject-each-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!