Search code examples
javajbosscdiwildfly-swarm

Is it possible to make use of a dependency CDI with wildfly?


I'm used to Spring framework dependency injection and stuff, so I'm really green with JBoss. I might be wanting to do something that is not possible.

In our company we started with a prototype that has all the dependency injection on it. We have one class declared this way:

@ApplicationScoped
public class MessageHandlerImpl implements MessageHandler {
    ...
}

and I inject it on another class like this:

@ApplicationScoped
public class MessageReceiverImpl implements MessageReceiver {

    @Inject
    MessageHandler messageHandler;
    ...

}

The prototype was accepted and now we are organizing this project isolating some common code on a core project.

Those injections were working fine until we separated it. More details about this problem was asked on this question: Ambiguous dependency with only one @ApplicationScoped class

I'm taking a step back and considering that maybe what I'm doing is not possible with wildfly-swarm or the whole concept that I'm trying is wrong.

What I would like to do is to have all the CDI done on my core project and only use it with an @Inject annotation on my dependent project. So in my dependent project I would have something like:

@ApplicationScoped
public class WSClient {

    @Inject
    MessageReceiver messageReceiver;

    ...

}

Well, that doesn't work because I get an Ambiguous dependency as you can see on the question I linked. I'm wondering if what I should be doing is use a Producer or something like that. Can anyone enlighten me on a valid approach for this, or maybe an alternative?


Solution

  • Producers are used when you want to instantiate a type in a certain, possibly varying, way and then just hand it over to CDI saying "Hey, if someone injects this type, give him this instance" (very simplified version of course). From what you described, you should be good enough with plain injection and bean creation, I don't see a need for producer.

    From both of your questions I can gleam that the injection in fact even works, but there are some ambiguities. By that I mean that one injection point has several possible candidates. Only in your case they are identical which means the class must have been loaded twice somehow, somewhere - keep digging in that direction.

    From the architecture point of view, with CDI it is perfectly ok (and I would say common) to extract your core as a CDI library which is then used by other parts of your project. Just make sure all of your archives are considered "bean archives". The easiest way to achieve that is to make sure you include beans.xml in them.