News Ticker

Using @Alternative in CDI application

Java EE CDI @Alternative

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 a very simple example that provides a shopping cart with a mock price list bean. Please note that this is an oversimplified example for the purpose of demonstrating the usage of alternatives in Java EE.

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 GeneratePriceList();
}
public class LivePriceList implements PriceList {
    public String GeneratePriceList() {
        // 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 GeneratePriceList() {
        // 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.GeneratePriceList();
    }

}

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.

Leave a Reply

%d bloggers like this: