在这个例子中,有两个注入的类,EntityManager和UserTransaction。我不明白为什么UserTransaction可以直接注入而不先注释它,但是EntityManager必须在一个单独的类中用@Produces定义和注释?
提前致谢。
CarManager.java
public class CarManager {
@Inject
private EntityManager em;
@Inject
private UserTransaction utx;
private Long id;
private Logger log = Logger.getLogger(CarManager.class.getSimpleName());
public void setId(Long id) {
this.id = id;
}
/**
* Returns either a new instance or a managed instance of {@link Car}.
* The produced entity should be dependent scoped to avoid incompatible proxies between
* JPA and CDI.
*/
@Produces
public Car getCar() {
if (id == null) {
log.info("Returning new instance of Car");
return new Car();
}
log.info("Finding instance of Car with id " + id);
return em.find(Car.class, id);
}
...
}
EntityManagerProducer.java
public class EntityManagerProducer {
@Produces
@PersistenceContext
private EntityManager em;
}
答案 0 :(得分:2)
因为UserTransaction
被称为预定义bean,EntityManager
因此不需要拥有自己的生成器。有关预定义bean的列表,请参阅25.4 Using Predefined Beans in CDI Applications。