19 January 2018 · Java CDI JEE

Dynamic injection in CDI

Create EnvironmentType enum:

public enum EnvironmentType { VAPP, PHYSICAL, CLOUD }

then create qualifier:

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
public @interface EnvironmentQualifier {
    EnvironmentType value();
}

... next create abstract class or interface Environment:

public interface Environment {
    Machine getMachine(String name);
}

then create EnvironmentLiteral to be able to select environment with string

public class EnvironmentLiteral extends AnnotationLiteral<EnvironmentQualifier> implements EnvironmentQualifier {

    private EnvironmentType type;

    public EnvironmentLiteral(EnvironmentType type) {
        this.type = type;
    }

    @Override
    public EnvironmentType value() {
        return type;
    }
}

... create EnvironmentFactory

public class EnvironmentFactory {

    @Inject
    @Any
    private Instance<Environment> environments;

    public Environment getEnvironment(EnvironmentType environmentType) {
        EnvironmentLiteral qualifier = new EnvironmentLiteral(environmentType);
        return environments.select(qualifier).get();
    }
}

and finally crate some implementations of Environment interface:

@EnvironmentQualifier(EnvironmentType.PHYSICAL)
public class PhysicalEnvironment implements Environment {
    @Override
    public Machine getMachine(String name) {
        ...
        return new Machine(name);
    }
}