Using @Alternative in CDI application
There are many scenarios where you might want to have more that one version of a bean and use it for different purposes. The typical justification for an alternative bean is for testing purposes where the alternative bean presents mock data. The benefit it that the live system that the ‘real’ bean must connect to in order to obtain live data is remote or just too time consuming to use during a test scenario. So a mock bean that provides static data is provided instead.
In this post I will set up an example that provides a shopping cart with a mock price list bean.
How to set up alternative bean implementations
The real and alternative bean must implement the same interface. In this example they implement the PriceList interface.
public interface PriceList { String priceList(); }
public class LivePriceList implements PriceList { public String priceList() { // connect to price list webservice or database return "Live Price List"; } }
The alternative bean is annotated @Alternative to identify it as the alternative implementation.
@Alternative public class MockPriceList implements PriceList { public String priceList() { // use hard code prices for testing return "Mock Price List"; } }
The PriceList bean can be injected using the interface as the type.
public class ShoppingCart { @Inject private PriceList priceList; public String ObtainPriceList(){ return priceList.priceList(); } }
As this example stands the real PriceList bean will be injected into the ShoppingCart by CDI when it is deployed.
Use the alternative bean
To use the alternative bean you must indicate the version of the PriceList bean use wish to use in the beans.xml file.
<beans ...> <alternatives> <class>com.readlearncode.alternatives.MockPriceList</class> </alternatives> </beans>
The fully qualified name of the alternative bean is specified.
Conclusion
When the application is deployed the CDI container will inject the alternative MockPriceList into the ShoppingCart bean.
Source Code
Source code for this example can be found in the ReadLearnCode GitHub repository.
Published on Java Code Geeks with permission by Alex Theedom, partner at our JCG program. See the original article here: Using @Alternative in CDI application Opinions expressed by Java Code Geeks contributors are their own. |