/java/

Using @Alternatives Annotation.

2015-07-05 11:01:45

package pl.btbw.shop;

public interface ShopEngine {
    String getName();
}
package pl.btbw.shop;

public class SimpleShop implements ShopEngine {

    public String getName() {
        return "Simple Shop";
    }
}
package pl.btbw;

import pl.btbw.shop.ShopEngine;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/")
public class App {

    @Inject
    private ShopEngine shopEngine;

    @GET
    public String testShop() {
        return shopEngine.getName();
    }

}

now "shopEngine.getName()" return "Simple Shop"

but you can inform CDI to take other implementation by:

package pl.btbw.shop;

import javax.enterprise.inject.Alternative;

@Alternative
public class RedShop implements ShopEngine {

    public String getName() {
        return "Red Shop";
    }
}

in this stage noting happen, we can add as many implementation as you want. to inform witch @Alternative should be use you have to add this to beans.xml

<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>

<beans beans_1_0.xsd&quot;="" http:="" java.sun.com="" javaee="" ns="" xml="" xmlns='"http://java.sun.com/xml/ns/javaee"' xmlns:xsi='"http://www.w3.org/2001/XMLSchema-instance"' xsi:schemalocation='"http://java.sun.com/xml/ns/javaee'>
<alternatives>
<class>pl.btbw.shop.RedShop</class>
</alternatives>
</beans>

now “shopEngine.getName()” return “Red Shop”

Github