为什么不能将2个EJB注入到互相注入的2个不同的托管bean中? [英] Why can't I inject 2 EJB's into 2 different managed beans that inject each other?

查看:117
本文介绍了为什么不能将2个EJB注入到互相注入的2个不同的托管bean中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ContactsBean

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

Details Bean

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

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

我不能这样做.每当我在细节bean中调用EJB时​​,它都会引发EJB异常和此异常.

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

违反了Bean验证约束 在执行自动Bean时 回调验证 事件:"prePersist"

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

有创意的人吗?谢谢

好,所以我发现使用requestScoped bean似乎导致了此问题.为什么会这样?

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

推荐答案

注入是在构造bean之后直接进行的.会话范围的Bean每个会话仅构造一次.会话范围比请求范围更广.一个会话中可以有多个请求.当当前有多个请求时,注入器将不知道它必须注入哪个范围的请求.甚至可能根本没有任何请求.

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.

要相互注入,接受者的范围必须与注入的对象相同或更窄.将会话作用域的bean注入请求作用域的bean就可以了.我建议您改走这条路线.

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.

与具体问题无关,我还建议您也重新考虑EJB方法.您真的需要将 same @EJB放在两个已经相互了解的bean上吗?我建议从DetailsBean中删除ContactsFacade,然后让DetailsBean将作业委派给ContactsBean.

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个EJB注入到互相注入的2个不同的托管bean中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆