freedev
freedev

Reputation: 30087

wildfly - use CDI with POJO

I would like use CDI with POJO.

Now have a Jaxrs Resteasy webapp running in Wildfly 10.1.0.Final.

There is a singleton which returns a ServiceImpl class:

public class ServiceFactory {

    private static Service service = new ServiceImpl();

    public static Service getEnvsApi()
    {   
       return service;
    }
}

And I would like use CDI inside ServiceImpl class

public class ServiceImpl extends Service {

   @Inject
   private MyData    myData;

   @Override
   public MyData getData()
   {
      return myData;
   }
}

but myData is always null.

Have I to start Weld manually?

Upvotes: 0

Views: 404

Answers (2)

Rouliboy
Rouliboy

Reputation: 1377

If your webapp is running in Wildfly you do not need to "start" Weld. Just use CDI API in your code and add beans.xml in webapp/WEB-INF (take a look at bean discovery mode of CDI) and CDI will be activated.

Regarding your problem, the problem is you instantiate Service via new operator which breaks CDI! Ss said in others answers, you must use @ApplicationScoped on the ServiceImpl and you do not need ServiceFactory.

Just declare ServiceImpl as @ApplicationScoped

@ApplicationScoped
public class ServiceImpl implements Service {

   @Inject
   private MyData    myData;

   @Override
   public MyData getData()
   {
      return myData;
   }

}

And then you can @Inject your Service:

@Inject
private Service service

Upvotes: 1

Simon Martinelli
Simon Martinelli

Reputation: 36173

You also must inject the Service in the ServiceFactory because if you instantiate it it is not under CDI control.

Probably you can completely remove the ServiceFactory and inject the Service everywhere you need it.

Upvotes: 0

Related Questions