Java EE 7 - @Decorator、@Stateless 和@PersistenceContext = nullpointerException

标签 java jakarta-ee ejb decorator cdi

我在 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/

相关文章:

Java Int Array - 存储的数字与指定的数字不同

java - 需要在纯 java(ee、servlet 和 POJO)中创建方法拦截器以在 weblogic 中使用,我可以使用什么来做到这一点?

java - gson.toJson() 在 Servlet 中抛出 StackOverflowError

jpa - 如何识别@PreUpdate 中的 EJB 实体属性更改?

java - 使用 Maven 为同一项目构建 war 和 Ear 文件

java - Itext7 - 嵌套表未在单元格内对齐

java - Android 添加 map 标记错误 : java. lang.IllegalStateException:不在主线程上

java - 准备好的语句失败(带有错误消息!)

java - Struts重定向问题

java - 在 session bean 中使用 EntityManager 时出错