EJB 注入和 EntityManager 都是空的

EJB injection and EntityManager are both null

我正在使用带有 GlassFish 5 的 eclipse。我正在使用 swing 制作一个三层应用程序。首先我创建了一个 JPA 项目,然后添加了 EJB Facet。 正在使用实体 classes 成功创建架构。

我的 EJB 注入和 EntityManager 注入出现空值。

在我的控制器中,我按如下方式注入了 EJB:

public class BookQueries {

    @EJB
    private  BookService bs;

    public BookQueries() {
    /*try {

        Context context = new InitialContext();         
        Object fObj = context
            .lookup("java:global/LMS/BookService!com.lms.service.BookService");
        bs=(BookService)fObj;
    }catch(NamingException e) {
        System.out.println("Naming Exception while lookup of bean object");
    }
    */
}

正如您在控制器构造函数中看到的那样,我也尝试了 JNDI 查找,但我仍然得到 null.Here 是我的 EJB class,我在其中注入了 EntityManager,它也是空的。

@Stateless
@LocalBean
public class BookService {

    @PersistenceContext(name = "LMS")
    EntityManager em;

}

这是我的 Persistence.xml 文件

<persistence-unit name="LMS">   
    <jta-data-source>jdbc/lms</jta-data-source>
    <properties>
        <property name="eclipselink.ddl-generation"
                  value="drop-and-create-tables" />
    </properties>
</persistence-unit>

我之前在 Eclipse 上制作了 Web 动态应用程序,在那里一切正常。

请让我知道我做错了什么。谢谢。

首先是后者,你的 BookService 应该有:

@PersistenceContext(unitName = "LMS") // not 'name'

或者如果没有其他 PU 在使用,您可以不使用任何 unitName 进行尝试。

那么关于您的 BookQueries 它本身是一个托管 bean 我在其中看不到任何与 bean 相关的注释吗?如果不是,那么 @EJB 将不会被初始化。例如,如果它是一个 Singleton bean 添加注释:

@Singleton
@Startup  // makes it to be initialized at app startup

@LocalBean

new BookQueries()那样做并不能使它得到管理,因此不会发生注入或类似的事情。您需要对其进行注释(或在 Glassfish 的控制面板或 beans.xml 中的某处配置它)才能成为已知的 bean。然后将它注入到一些托管上下文(UI class?),例如使用 @Inject@Resource 就像你注入 BookService.

此外,我建议您查看是否应该使用 @Inject@Resource 之类的注释,而不是 @EJB