1

我想将一个单例 EJB 注入我的 POJO 类。使用新的 EJB 3.1 规范,是否可以将 EJB 注入 POJO?我知道在 EJB 3.0 中,@EJB 注释可用于注入 EJB,但这不适用于简单的 POJO。 @javax.inject.Inject也不适合我。

还有一件事是,容器资源和非容器资源有什么区别?我如何实现它,我使用的是 JBoss AS 7.1.1。

4

2 回答 2

6

EE 是围绕组件类(EJB、servlet 等)的思想设计的。EE容器只有在控制对象的创建时才能进行注入,这不适用于POJO,所以不能对POJO对象使用EE注入。

要使 CDI 正常工作,您需要添加META-INF/beans.xml到存档中。即使这样,您也无法使用new. 您总是必须让容器创建实例,所以要么@Inject是 POJO,然后@Inject是 EJB,要么使用javax.enterprise.inject.spi.BeanManager.

于 2013-10-04T15:51:11.103 回答
3

@EJB won't work for you so you have only two options - JNDI lookup or using CDI. Something like

@Inject
private MyEJB ejb;

should work for you. Also check that you have beans.xml in the WEB-INF folder in order to activate CDI container.

And for the difference - it is almost the same (while it's recommended to use @Inject) with only exception - you still have to use @EJB for injecting remote beans.

Reason why you can't use service = new ServiceClass(); is that service object will not be managed by the container - that means that no injections will be peformed after creation of this class because container is no longer in control of this object. Very naively said, if you do

@Inject
ServiceClass service;

container will create new instance, then perform injections and return it to you.

于 2013-10-04T11:37:23.313 回答