gpt4 book ai didi

jpa - 使用 CDI + WS/RS + JPA 构建应用程序

转载 作者:行者123 更新时间:2023-12-04 17:58:27 25 4
gpt4 key购买 nike

@Path(value = "/user")
@Stateless
public class UserService {

@Inject
private UserManager manager;

@Path(value = "/create")
@GET
@Produces(value = MediaType.TEXT_PLAIN)
public String doCreate(@QueryParam(value = "name") String name) {
manager.createUser(name);

return "OK";
}
}

这是用户管理器 impl
public class UserManager {

@PersistenceContext(unitName = "shop")
private EntityManager em;

public void createUser(String name) {
User user = new User();
user.setName(name);
// skip some more initializations
em.persist(user);
}
}

问题是如果我没有将 UserService 标记为 @Stateless 那么管理器字段为空

但是如果我标记@Stateless,我可以注入(inject)管理器字段,并且应用程序可以正常工作,因为我可以将数据保存到数据库中

只是想知道,这背后的原因是什么?

这是连接应用程序的首选方式吗?

好吧,我正在考虑将 EntityManager 拉出给生产者,以便可以共享

最佳答案

the problem is if I do not mark UserService as @Stateless then the manager field is null



要进行注入(inject),该类必须是托管组件,例如 Enterprise Bean、Servlet、过滤器、JSF 托管 bean 等或 CDI 托管 bean (这是 Java EE 6 的新部分,您可以使用 CDI 使任何类成为托管 bean)。

那么,如果您不将 JAX-RS 端点设为 EJB,如何启用注入(inject)?这在 JAX-RS and CDI integration using Glassfish v3 中有很好的解释。 :

There are two ways CDI managed beans are enabled:

  1. instantiated by CDI, life-cycle managed by Jersey. Annotate with @ManagedBean and optionally annotate with a Jersey scope annotation.

  2. instantiated and managed by CDI. Annotate with a CDI scope annotation, like @RequestScoped (no @ManagedBean is required)



我还建议检查以下资源。

and is this the preferred way to wiring the application?



我会说是的。 CDI 非常好而且……你不喜欢注入(inject)吗?

well, I am thinking to pull out the EntityManager to a producer, so that it can be shared



之间共享什么?为什么?在您的情况下,您应该使用 EntityManager生命周期仅限于单个事务(事务范围的持久性上下文)。换句话说,不要共享它(也不要担心为每个请求打开和关闭它,这不是一个昂贵的操作)。

引用
  • JPA 2.0 规范
  • 第 7.6 节“容器管理的持久性上下文”
  • 第 7.6.1 节“容器管理的事务范围持久性上下文”
  • 第 7.6.2 节“容器管理的扩展持久性上下文”

  • 资源
  • Dependency Injection in Java EE 6 - Part 1
  • Introducing the Java EE 6 Platform: Part 1
  • TOTD #124: Using CDI + JPA with JAX-RS and JAX-WS
  • 关于jpa - 使用 CDI + WS/RS + JPA 构建应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3744396/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com