Question

Assuming I have a data access object that I've already written, I'd like to be able to use CDI to inject that into say, a service class. Furthermore, I have two implementations of that DAO.

My understanding of CDI is that I'd have to annotate my DAO implementation class so that CDI would know which implementation to inject.

The problem is, the DAO is in a .jar file. By annotating it with CDI annotations, I'm using JavaEE imports in a non-JavaEE class.

For example, let's say I have the following class

public class BusinessService {
    @Inject @SomeMybatisQualifier AccountDAO accountDao;
    ...
}

The @Inject annotation comes from javax.inject.Inject. Now, this service class is dependent on a JavaEE environment.

Can someone please explain to me what I'm missing? How do I inject a non-annotated class into another non-annotated class? This is fairly simple with Spring.

Was it helpful?

Solution

I agree with LightGuard if there's enough classes. But for a couple, why not just produce them with @Produces?

Here's a decent example of implementing your own producer:

Depedency inject request parameter with CDI and JSF2

You should be able to write return new MyObject(); and you can add whatever qualifiers you want

Not sure what's unclear but here's the gist of things: For CDI to scan a jar for beans it must have a beans.xml. Else it will not be scanned and thus not available for injects.A String is not available either. If you try to inject a String say;

@Inject
String myString;

CDI will have no clue what to give you just like your jar. But I know what String I want (a requestparam) and I can let CDI know as well. How? Well I supply a qualifier @RequestParam to my producer (see example again) and now when I want to use it in client code I do it like this:

@Inject
@RequestParam
String myString;

You can do the same thing. Have a producer and just create a new instance of whatever you need and then return it. Now CDI will know just how to dependency inject that particular bean.

Now say you have 40 classes. Then it gets messy to produce them and you want to make sure it gets scanned instead. Then you write your own little extension, observe when CDI is about to scan and instruct it to scan additional jars. Such extension is probably easy to write but I don't know the details because I have not written any extensions like it

OTHER TIPS

By far, the easiest thing would be to create a CDI extension to add the classes in the jar (because there's no beans.xml in that jar so it won't be picked up by CDI) and add additional qualifiers to the metadata.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top