问题描述
我已经阅读过关于CDI中的@Produces注释,但我不明白它的用法。
I have read about the @Produces annotation in CDI, but I don't understand its usage.
public class Resources {
// Expose an entity manager using the resource producer pattern
@SuppressWarnings("unused")
@PersistenceContext
@Produces
private EntityManager em; //
@Produces
Logger getLogger(InjectionPoint ip) { //
String category = ip.getMember()
.getDeclaringClass()
.getName();
return Logger.getLogger(category);
}
@Produces
FacesContext getFacesContext() { //
return FacesContext.getCurrentInstance();
}
}
取自:
容器如何知道调用生产者方法?如果我注入一个EntityManager,容器如何调用@produces EntityManager?如何调用getLogger生成器方法?
How does the container know to call a producer method? If I inject an EntityManager, how does the container call the @produces EntityManager? And how would a getLogger producer method get called?
我也没有看到解决所有麻烦的原因。
I also don't see the reason to go through all of the trouble.
推荐答案
给出了注释:
Section 3.3 of the CDI specification gives a pretty good high level overview of the use of the @Produces
annotation:
生成器方法充当要注入的对象的源,其中:
•要注入的对象不需要是bean的实例,或者
•要注入的对象的具体类型可能在运行时有所不同,或者是
•对象需要一些不是由bean构造函数执行的自定义初始化。
比如说,你想在Jav之间架起桥梁一个EE托管组件,如实体管理器和其他CDI组件,您可以使用 @Produces
注释。另一个好处是您可以避免在整个数据域层中复制 @PersistenceContext
注释。
Let's say, for example, that you wanted to bridge between a Java EE managed component like an entity manager and other CDI components, you could utilize the @Produces
annotation. Another benefit being that you avoid having to duplicate @PersistenceContext
annotations throughout your data domain layer.
class A {
@PersistenceContext // This is a JPA annotation
@Produces // This is a CDI 'hook'
private EntityManager em;
}
class B {
@Inject // Now we can inject an entity manager
private EntityManager em;
}
另一个方便的用途是绕过没有CDI友好bean的库(例如,没有默认构造函数):
Another handy use is for getting around libraries that do not have CDI friendly beans (for example, no default constructors):
class SomeTPLClass {
public SomeTPLClass(String id) {
}
}
class SomeTPLClassProducer {
@Produces
public SomeTPLClass getInstance() {
return new SomeTPLClass("");
}
}
生产的Javadoc也显示了一个有趣的(但公平的)罕见的情况)生成一个命名集合,以后可以注入其他托管bean(非常酷):
The Javadoc for produces also shows an interesting (but fairly rare case) of producing a named collection that can later on be injected into other managed beans (very cool):
public class Shop {
@Produces @ApplicationScoped
@Catalog @Named("catalog")
private List<Product> products = new LinkedList<Product>(8);
//...
}
public class OrderProcessor {
@Inject
@Catalog
private List<Product> products;
}
容器负责处理标有@Produces注释的所有方法和字段,并且通常在部署应用程序时执行此操作。然后,处理后的方法和字段将根据需要用作托管bean的注入点解析的一部分。
The container is responsible for processing all methods and fields marked with a @Produces annotation, and will normally do this when your application is deployed. The processed methods and fields will then be used as part of the injection point resolution for managed beans, as needed.
这篇关于请解释CDI中的@Produces注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!