1

I'm having trouble with CDI conditional injection to use a kind of Strategy in EJB's injections.

My actual scenario is that:

public class someManagedBean {

    @Inject 
    @MyOwnQualifier(condition = someBean.getSomeCondition()) // not work because someBean is not already injected at this point
    private BeanInterface myEJB;

    @Inject
    SomeBean someBean;
}

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface MyOwnQualifier {
    SomeCondition condition();
}

public class BeanInterfaceFactory {
    @Produces
    @MyOwnQualifier(condition = RoleCondition.ADMIN) 
    public BeanInterface getBeanInterfaceEJBImpl() {
        return new BeanInterfaceEJBImpl();
    }
}

public enum RoleCondition {
    ADMIN("ADMIN User");
}

Ok, scenario explained. Now the problem is that I need to get the value from someBean.getSomeCondition() that returns a RoleCondition, necessary for my @MyOwnQualifier. But at this time someBean is not already injected by CDI.

How I can make this line to work?

@Inject 
@MyOwnQualifier(condition = someBean.getSomeCondition()) // not work because some is not already injected at this point
private BeanInterface myEJB;

How is the right way to dynamically inject beans using qualifiers based on another injection's property value?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Johnny Willer
  • 3,717
  • 3
  • 27
  • 51
  • 1
    I don't really see how this can ever work since annotations are compile-time things, and someBean.getSomeCondition() evaluates at runtime. I'd more think you want to create a producer which can conditionally provide an instance. https://docs.jboss.org/weld/reference/1.0.0/en-US/html/producermethods.html – Gimby Mar 07 '16 at 13:53
  • There is no such thing like `beforeConstruct` to evaluate some values before try to inject? – Johnny Willer Mar 07 '16 at 13:55

1 Answers1

4

Try this...

public class someManagedBean {

    @Inject 
    @MyOwnQualifier
    private BeanInterface myEJB;
}

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface MyOwnQualifier {
    SomeCondition condition();
}

public class BeanInterfaceFactory {

    @Inject
    SomeBean someBean

    @Produces
    @MyOwnQualifier
    public BeanInterface getBeanInterfaceEJBImpl() {
        if(someBean.getCondition()) {         
            return new BeanInterfaceEJBImpl();
        } else {
           ....
        }
    }
}

public enum RoleCondition {
    ADMIN("ADMIN User");
}
fantarama
  • 862
  • 6
  • 14