java 8 - Instantiate list of objects with CDI -
i refactoring legacy code , came across snippet below. how avoid instantiation of 'companyauditor' class , use cdi hanldle it?
return compdao.getall() .stream() .map( companyauditor::new ) .collect( collectors.tolist() );
the way define constructor without arguments companyauditor, create new instances using javax.enterprise.inject.instance.get. , afterwards pass arguments using public methods. therefore constructor argument must separated 1 without arguments , additional public method set argument. also, must write own lambda expression, more complicated companyauditor::new.
full example:
@inject @new // javax.enterprise.inject.new request new object private instance<companyauditor> auditorinjector; public list returnallwrappedauditors() { return compdao.getall() .stream() .map( ca -> { companyauditor auditor = auditorinjector.get(); auditor.setwrappedobject( ca ); return auditor; }) .collect( collectors.tolist()); }
afternote:
cdi not easy use when dynamically constructing objects, excells in injecting dependencies. therefore bit more verbose calling constructor create new objects.
cdi beans must have either constructor without parameters or parameters annoted @inject (which not in case) see java ee 7 tutorial
Comments
Post a Comment