java - How to use dependency injection in JAXB unmarshalled objects? -


i have factory class

@applicationscoped /* 'applicationscoped' not must */ class myfactory {     @inject    private iservice aservice;     ... } 

and jaxb annotated class

@xmlrootelement(name = "item") class anitem {    @inject   myfactory myfactory;    ... } 

anitem instantiated jaxb xml file. problem myfactory null. if replace

... myfactory myfactory = new myfactory(); ... 

then myfactory.aservice null.

how can use dependency injection within classes created jaxb?

the following solution inspired block of adam warski, see beanmanager javadoc

at first i'll need 2 utility methods:

import javax.enterprise.inject.spi.bean; import javax.enterprise.inject.spi.beanmanager; import javax.naming.initialcontext; import javax.naming.namingexception;  public class utils {   public static beanmanager getbeanmanager() {     try {         initialcontext initialcontext = new initialcontext();         return (beanmanager) initialcontext.lookup("java:comp/beanmanager");     } catch (namingexception e) {         throw new runtimeexception("failed retrieve beanmanager!", e);     }   }    public static <t> t getbean(class<t> c) {     t result = null;     beanmanager bm = getbeanmanager();     set<bean<?>> beans = bm.getbeans(c);     if (! beans.isempty()) {         bean<?> bean = beans.iterator().next();         result = c.cast(bm.getreference(bean, c, bm.createcreationalcontext(bean)));     }     return result;   } } 

class anitem has changed this:

@xmlrootelement(name = "item") class anitem {    myfactory myfactory = utils.getbean(myfactory.class);    ... } 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -