Java EE 7 - @Decorator,@Stateless和@PersistenceContext = nullpointerException [英] Java EE 7 - @Decorator, @Stateless and @PersistenceContext = nullpointerException
问题描述
我在java ee 7(glassfish 4)中使用了decorator模式。
I'm using decorator pattern in java ee 7 (glassfish 4).
我有这个装饰器
@Decorator
public class FooIndexer implements FooService {
@Inject
@Delegate
FooService fooService;
private Logger logger = Logger.getLogger(FooIndexer.class.getName());
//@Inject
//Indexer indexer;
@Override
public Foo create(Foo foo, boolean index) {
fooService.create(foo, index);
if (index) {
System.out.println("Im in");
}
return foo;
}
}
这个ejb类
@Stateless(name = "fooService")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@DeclareRoles({"ADMINISTRATOR", "USER"})
public class FooServiceImpl implements FooService {
@PersistenceContext(unitName = "foo")
private EntityManager em;
@Resource(lookup="java:comp/EJBContext")
private SessionContext ctx;
/** CRUD **/
@RolesAllowed("ADMINISTRATOR")
public Foo create(Foo foo, boolean index) {
Principal cp = ctx.getCallerPrincipal();
System.out.println(cp.getName());
em.persist(foo);
return foo;
}
}
当我使用这个装饰器模式时,EJB中的EntityManager null(没有装饰器,一切顺利)。我认为是因为装饰器使用@Inject而不是@EJB注解(@EJB注释不能在@Decorator中使用),并且EntityManager没有被注入。
When I use this decorator pattern, EntityManager in EJB is null (without decorator, everything goes fine). I supose is because of decorator use @Inject instead of @EJB annotation (@EJB annotation can't be used in @Decorator), and EntityManager is not being injected.
但是,如何使用@decorator注入实体管理员?
But, what can I do to get entitymanager will be injected using @decorator?
谢谢
Thank you
推荐答案
尝试在META-INF中添加一个空的beans.xml,这将激活CDI bean发现。我的项目有一个类似的问题。
Try adding an empty beans.xml in your META-INF, this will activate CDI bean discovery. I had a similar issue with my project.
请参阅oracle doc这里: http://docs.oracle.com/javaee/6/tutorial/doc/gjbnz.html
See oracle doc here : http://docs.oracle.com/javaee/6/tutorial/doc/gjbnz.html
您必须创建一个空的beans.xml文件,以向GlassFish Server指示您的应用程序是CDI应用程序。这个文件可能在某些情况下有内容,但不能像这样的简单应用程序。
You must create an empty beans.xml file to indicate to GlassFish Server that your application is a CDI application. This file can have content in some situations, but not in simple applications like this one.
http://docs.oracle.com/javaee/6/tutorial/doc/gjbju.html#gjcvh
祝你好运!
Alexander Kirilov
Alexander Kirilov
这篇关于Java EE 7 - @Decorator,@Stateless和@PersistenceContext = nullpointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!