简体   繁体   中英

CDI Injecting EJB (Stateless) from lib jar

I'm having trouble injecting dao bean declared on a lib jar. So I have a jar (mine) with a persistence context, entities and daos. Here is a dao example :

@Stateless
public class SomeDao {

  @PersistenceContext
  private EntityManager em;

  ...

}

Now I want to use this dao on my main application.

A jax-rs use case :

@Path("rs")
public class WebService{

  @Inject
  private SomeDao dao;

  @POST
  public Response doPost(){
    //dao is injected but nullpointer thrown on EntityManager
    dao.doSomething();
  }
  ...
}

There is a beans.xml in both project (under META-INF/ for lib, WEB-INF/ for the web application). like this one :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
    http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

</beans>

------------- Edit ------------

I've just found out if I remove the @Stateless annotation and the producer it works. So the problem is in fact : how to inject with CDI an EJB declared on an lib jar.

Firstly, if this a jar you create and not a third party just, simply add a beans.xml in the correct location for the jar and you'll have those objects available for injection. That's the easiest way.

If it is a third part jar, your next best idea is to create a portable extension and listen to the BeforeBeanDiscovery in CDI 1.0 or AfterTypeDiscovery in CDI 1.1 and call the addAnnotatedType method to add in those classes you need from the jar. You'd create this extension in your war / ear classpath.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM