Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent for @Conditional in CDI

Tags:

java

inject

cdi

I have two classes with post construct initialization, and i need one of them to be injected based on a vm argument. I have done this kind of conditional injection in spring using @Conditional annotation, however i could not find any equivalent in CDI. Can some one please help me with this.

The code goes something like this,

public void impl1{
    @PostConstruct
    public void init(){
       ....
    }
    ....
}


public void impl2{
    @PostConstruct
    public void init(){
       ...
    }
    ....
}

If vmargument type=1, impl1 has to be injected and if type=2, impl2 has to be injected

like image 733
vamsi Avatar asked Apr 10 '26 01:04

vamsi


1 Answers

For runtime decision (without changing your beans.xml), you basically have two options:

Option 1: use a producer method

@Produces
public MyInterface getImplementation() {
   if(runtimeTestPointsTo1)  return new Impl1();
   else                      return new Impl2();
}

Drawback: you leave the world of bean creation by using new, therefore your Impl1 and Impl2 cannot @Inject dependencies. (Or you inject both variants in the producer bean and return one of them - but this means both types will be initialized.)

Option 2: use a CDI-extension

Basically listen to processAnotated() and veto everything you don't want. Excellent blog-entry here: http://nightspawn.com/rants/cdi-alternatives-at-runtime/

like image 123
mtj Avatar answered Apr 12 '26 15:04

mtj