我在 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 为空(没有装饰器,一切正常)。我想是因为装饰器使用@Inject 而不是@EJB 注释(@EJB 注释不能在@Decorator 中使用),并且没有注入(inject)EntityManager。
但是,我该怎么做才能使用@decorator 注入(inject)entitymanager?
谢谢
最佳答案
尝试在您的 META-INF 中添加一个空的 beans.xml,这将激活 CDI bean 发现。我的项目也遇到了类似的问题。
请在此处查看 Oracle 文档:http://docs.oracle.com/javaee/6/tutorial/doc/gjbnz.html
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
祝你好运!
亚历山大·基里洛夫
关于Java EE 7 - @Decorator、@Stateless 和@PersistenceContext = nullpointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17217282/