我想将一个单例 EJB 注入我的 POJO 类。使用新的 EJB 3.1 规范,是否可以将 EJB 注入 POJO?我知道在 EJB 3.0 中,@EJB 注释可用于注入 EJB,但这不适用于简单的 POJO。
@javax.inject.Inject
也不适合我。
还有一件事是,容器资源和非容器资源有什么区别?我如何实现它,我使用的是 JBoss AS 7.1.1。
EE 是围绕组件类(EJB、servlet 等)的思想设计的。EE容器只有在控制对象的创建时才能进行注入,这不适用于POJO,所以不能对POJO对象使用EE注入。
要使 CDI 正常工作,您需要添加META-INF/beans.xml
到存档中。即使这样,您也无法使用new
. 您总是必须让容器创建实例,所以要么@Inject
是 POJO,然后@Inject
是 EJB,要么使用javax.enterprise.inject.spi.BeanManager
.
@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.