通过 CDI 在 EntityListener 中注入 EJB 失败 (JPA 2.1)

Injection of EJB in EntityListener via CDI fails (JPA 2.1)

我正在尝试将 @Stateless EJB 注入到我的 EntityListner 中。我的 EntityListener 的 @PrePresist 方法被调用,但注入的 EJB 解析为 null,因此抛出 NullPointerException。

public class MyEntityListener {

    @Inject 
    private MyService myService;  // @Stateless EJB

    @PrePersist
    public void prePersist(MyEntity entity) {
        final Foo foo = myService.getFoo(); // !! NPE thrown here!!
        entity.setFoo(foo);
    }
}

我在 SO 上发现的以前的问题正在处理这个问题,即 JPA 确实只从 JPA 2.1 提供 CDI,但不为 JPA 2.0 提供,但我使用的是 JPA 2.1。那么这里还有什么问题?

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" 
    xmlns="http://xmlns.jcp.org/xml/ns/persistence"    
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
>
      <persistence-unit name="MY_PU" transaction-type="JTA">
      <jta-data-source>jdbc/local</jta-data-source>
      <exclude-unlisted-classes>false</exclude-unlisted-classes>
      <properties>
          <property name="eclipselink.logging.level" value="ALL" />
      </properties>
   </persistence-unit>
</persistence>

将我的 EJB 注入到其他会话 bean 中工作正常,无论是 EJB 注入 (@EJB) 还是 CDI 注入 (@Inject)。它仅在 EntityListner 中失败。

我正在使用 GlassFish 4.1 和 EclipseLink 2.5.2

相关问题: Injecting a SessionScoped Stateful bean in EntityListener

代码没有问题,这个行为是由这个错误引起的:

https://bugs.eclipse.org/bugs/show_bug.cgi?id=438105

该错误已在 EclipseLink 2.6.0 中修复。此版本的更新解决了我的问题。

http://www.eclipse.org/eclipselink/downloads/