注入 EntityManager 时的奇怪行为

发布于 2025-01-07 23:45:22 字数 1539 浏览 3 评论 0原文

我观察到一些关于注入 EntityManager 的奇怪行为。

以下是工作代码的精简版本:

Bean.java

@RequestScoped
@Named
public class Bean {

    @Inject
    private Service service; // +getter

    // few variables + getters/setters

    public String getMessage() {
        return getService().message();
    }

}

Service.java

@Stateless
@LocalBean
public class Service {

    @PersistenceContext
    private EntityManager entityManager; // +getter

    public String message() {
        return "[" + getEntityManager() + "]";
    }

}

cdi.xhtml

<h:body>
    <h:outputText value="#{bean.message}" />
</h:body>

但是我需要在创建 <强>服务。因此在工厂类中添加了以下生产者方法。

    @Produces
    @QService
    public Service createService() {
        Service service;

        service = new Service();
        // Some processing
        return service;
    }

并在类 Bean 的注入点添加相同的限定符 QService

    @Inject
    @QService
    private Service service; // +getter

现在,EntityManager NOT 被注入到 Service 类中,它仍然为 null。

我无法理解这种行为。有人可以解释一下吗?

I observed some strange behavior regarding injecting EntityManager.

Following is stripped down version of working code:

Bean.java

@RequestScoped
@Named
public class Bean {

    @Inject
    private Service service; // +getter

    // few variables + getters/setters

    public String getMessage() {
        return getService().message();
    }

}

Service.java

@Stateless
@LocalBean
public class Service {

    @PersistenceContext
    private EntityManager entityManager; // +getter

    public String message() {
        return "[" + getEntityManager() + "]";
    }

}

cdi.xhtml

<h:body>
    <h:outputText value="#{bean.message}" />
</h:body>

But I needed to do some processing, while creating Service. So added following producer method, in factory class.

    @Produces
    @QService
    public Service createService() {
        Service service;

        service = new Service();
        // Some processing
        return service;
    }

and added same qualifier QService at injection point in class Bean.

    @Inject
    @QService
    private Service service; // +getter

Now, EntityManager is NOT injected in class Service, it remains null.

I'm not able to understand this behavior. Can someone explain this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别忘他 2025-01-14 23:45:22

我认为问题在于这一行:

service = new Service();

由于 Service 是一个 EJB,它的生命周期由容器管理。你可以调用new,但我猜你不会得到一个EJB,而是一个纯java类。

尝试注入服务 EJB 而不是创建新实例。

I think the problem is this line:

service = new Service();

Since Service is an EJB it's lifecycle is managed by the container. You are allowed to call new but I guess you will not get an EJB but a pure java class.

Try to inject the Service EJB instead of creating a new instance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文