java - Please explain the @Produces annotation in CDI -
i have read @produces annotation in cdi, don't understand usage.
public class resources { // expose entity manager using 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(); }
}
taken from: http://www.jboss.org/jdf/quickstarts/jboss-as-quickstart/guide/greeterquickstart/#greeterquickstart-
how container know call producer method? if inject entitymanager, how container call @produces entitymanager? , how getlogger producer method called?
i don't see reason go through of trouble.
section 3.3 of cdi specification gives pretty high level overview of use of @produces
annotation:
a producer method acts source of objects injected, where:
• objects injected not required instances of beans, or
• concrete type of objects injected may vary @ runtime, or
• objects require custom initialization not performed bean constructor.
let's say, example, wanted bridge between java ee managed component entity manager , other cdi components, utilize @produces
annotation. benefit being avoid having duplicate @persistencecontext
annotations throughout data domain layer.
class { @persistencecontext // jpa annotation @produces // cdi 'hook' private entitymanager em; } class b { @inject // can inject entity manager private entitymanager em; }
another handy use getting around libraries 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(""); } }
the javadoc produces shows interesting (but rare case) of producing named collection can later on injected 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; }
the container responsible processing methods , fields marked @produces annotation, , when application deployed. processed methods , fields used part of injection point resolution managed beans, needed.
Comments
Post a Comment