I got 2 beans.
The first one is the model I use in production, Model
.
@Named("model")
@RequestScoped
public class Model{
}
The second one is the extension of Model
that I use for testing.
@Named("modelTest")
@RequestScoped
public class ModelTest extends Model{
}
How can I force CDI to select Model
by default?
Since you want to change the 'default' bean for given type and you don't want to use qualifiers, I assume the original bean is not to be injected anywhere. Therefore, what you are probably after is either an alternative or a specialization.
If we talk about alternatives, you need to mark the new bean with @Alternative
annotation and also 'select' it - that can be done on a per bean archive basis in beans.xml
or simply globally with @Priority(int)
. Here is a code snippet:
@Named("modelTest")
@RequestScoped
@Alternative
@Priority(1) // "activates"/selects the alternative
public class ModelTest extends Model{
}
With a selected alternative, whenever you inject the previous type (Model
), CDI will instead inject this alternative (ModelTest
), as it fits the injection point as well.
Secondary option is specialization. It is very similar to alternatives but stricter in a way that the original bean is 'discarded', you can read more about that in CDI spec. Specialization also comes with qualifier and bean name inheritance (not the scope though!). There is also no need to select the bean (as opposed to alternatives). Here is the code:
@RequestScoped
@Specializes
public class ModelTest extends Model{
// bean name with be inherited automatically as "model"
}
Note that a bean can only have one bean name at a time, as per specification. Therefore if you inherit one name and declare another, you will be getting errors - alter your code accordingly.