dynamic cdi with @Any

41 Views Asked by At

In our Java EE application, we process different file types. But instead of injecting all types as

@Any
@Inject
private Instance<FileHandler> handler

We do it with a big switch. All handler to extend from FileHandler, it's a abstract class, not an interface. Is there a way to make it generic? From what I can see with Instance, you still have to pass the class file of the implementation you wanna use.

@Inject
private XmlHandler xmlHandler;

@Inject
private CsvHandler csvHandler;


public void method(String fileType) {
    switch (fileType) {
        case "xml":
            xmlHandler.handle();
            break;
        case "csv":
            csvHandler.handle();
            break;
    }
}
1

There are 1 best solutions below

1
Ebuzer Taha KANAT On

Enum to list all of them:

public enum FileHandlers {
    XmlHandler,
    CsvHandler
}

Qualifier to specify:

@Target({ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier 
public @interface FileHandlerChooser {
FileHandlers choose();
}

Implementation:

@FileHandlerChooser(choose = FileHandlers.XmlHandler)
public class XmlHandler implements FileHandler {

...

}

Injection:

@Inject
@FileHandlerChooser(choose = FileHandlers.XmlHandler)
private FileHandler fileHandler;