问题
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