Search code examples
javajakarta-eecdi

CDI @Alternative annotation with @ApplicationScoped


I have the following interface:

public interface StackConfigurationService {
    List<StackConfiguration> getStacksByAppId(String appId) throws ConfigurationException;
}

With two implementations:

@ApplicationScoped
public class StackConfigurationServiceImpl implements StackConfigurationService {
    public List<StackConfiguration> getStacksByAppId(String appId) throws ConfigurationException { ... }
}

and

@Alternative
@ApplicationScoped
public class StackConfigurationMockService implements StackConfigurationService {
    public List<StackConfiguration> getStacksByAppId(String appId) throws ConfigurationException { ... }
}

The beans.xml contains the following:

<?xml version="1.0" encoding="UTF-8"?>
    <beans 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 
    http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

    <alternatives>
        <class>my.app.StackConfigurationMockService</class>
    </alternatives>
</beans>

However, CDI never uses the mock implementation of the service. Is the @ApplicationScoped annotation interfering in any way?


Solution

  • It was working all along. I was changing the settings in beans.xml, rebuilding and restarting the server, but the problem was in the browser. I was using the same tab and simply hitting refresh after each server restart. I assume the server cached the classes for that session. Opening in a new tab solved the problem.