10.2.7.4. Override an Injection with an Alternative
Summary
Alternative beans let you override existing beans. They can be thought of as a way to plug in a class which fills the same role, but functions differently. They are disabled by default. This task shows you how to specify and enable an alternative.
Procedure 10.5. Override an Injection
This task assumes that you already have a
TranslatingWelcome
class in your project, but you want to override it with a "mock" TranslatingWelcome class. This would be the case for a test deployment, where the true Translator bean cannot be used.
Define the alternative.
@Alternative @Translating public class MockTranslatingWelcome extends Welcome { public String buildPhrase(string city) { return "Bienvenue à " + city + "!"); } }
Substitute the alternative.
To activate the substitute implementation, add the fully-qualified class name to yourMETA-INF/beans.xml
orWEB-INF/beans.xml
file.<beans> <alternatives> <class>com.acme.MockTranslatingWelcome</class> </alternatives> </beans>
Result
The alternative implementation is now used instead of the original one.