【问题标题】:How Variable of an Interface is Working in JAVA and Calling the Methods of Interface?接口的变量如何在JAVA中工作并调用接口的方法?
【发布时间】:2014-09-23 16:13:29
【问题描述】:

我知道 Java 接口的以下所有规则:

  1. 您不能实例化接口。
  2. 接口不包含任何构造函数。
  3. 接口中的所有方法都是抽象的。
  4. 接口不能包含实例字段。可以出现在接口中的唯一字段必须声明为 static 和 final。
  5. 接口未被类扩展;它由一个类实现。
  6. 一个接口可以扩展多个接口。

现在我的问题是我们如何创建接口 EntityManager 的变量并使用它的方法,如下面的代码:

import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateful
public class Movies {

    @PersistenceContext(unitName = "movie-unit")
    private EntityManager em;   // Here declaring a variable of an Interface

    public void addMovie(Movie movie) throws Exception {
        em.persist(movie);      // Here using variable of an Interface to call its method
    }
}

请对此稍加说明,以便我清楚了解这段代码的工作原理!

【问题讨论】:

    标签: java jakarta-ee interface entitymanager


    【解决方案1】:

    您似乎唯一缺少的是dependency injection。这里,

    @PersistenceContext(unitName = "movie-unit")
    private EntityManager em; // <-- this is an instance of a class that implements the
                              // EntityManager interface. Interfaces (as you note)
                              // cannot be directly instantiated.
    

    容器使用现场检查并“看到”@PersistenceContext(unitName = "movie-unit") 注释。然后它注入适当的实例。根据PersistenceContextJavadoc,

    表示对容器管理的EntityManager 及其关联的持久性上下文的依赖。

    容器管理它。

    【讨论】:

      【解决方案2】:

      你没有在这里创建任何东西,容器是。您所做的只是声明要注入的依赖项,这就是 DI 在 JavaEE 中的工作方式。对正在发生的事情的一个非常简单的看法:

      • 您的Movies EJB 是容器中的proxied

      • 代理自省您的类并发现您声明的注释以及您声明它的字段

      • 容器向代理提供EntityManager 的实例,从而使其可用于您的实现。

      Presto:即时EntityManager。注意到你在这个过程中参与的程度有多少?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-17
        • 1970-01-01
        • 2019-12-27
        • 1970-01-01
        • 2021-09-30
        相关资源
        最近更新 更多