2
votes

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.

1
"Since this dao bean is declared on a different jar I should create a provider in order to inject it" where have you read this? It's not true. - Adrian Mitev
That depends on which CDI impl you're using. Because it's in a different jar, it's actually in a different Bean Descriptor Archive (BDA), to my knowledge, OpenWebBeans is the only CDI implementation which ignores BDA boundaries. - LightGuard
The implementation is weld. - Ghetolay
@Adrian you're right big misunderstanding from me. Problem seems to because of the EJB annotation (@Stateless). - Ghetolay

1 Answers

0
votes

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.