Search code examples
cdijava-ee-7wildfly-10

@Specializes in Wildfly 10.1.0


We are trying to use alternative bean instance injection for our integration test suite deployed on a Wildfly 10.1.0 server.

According to the CDI 1.2 spec, a possible solution to do so would be to use the @Specializes annotation on an alternative deployed in the integration test archive only.

However, the default implementation is always injected. We tried @Specializes on managed beans, session beans, and tried to select the alternatives in the beans.xml file.

The following example illustrate the issue:

BeanInterface.java

public interface BeanInterface {
    void work();
}

Implementation1.java

@Dependent
public class Implementation1 implements BeanInterface {
    @Override
    public void work() {
        System.out.println("test 1");
    }
}

Implementation2

@Dependent
@Alternative
@Specializes
public class Implementation2 extends Implementation1 {
    @Override
    public void work() {
        System.out.println("test 2");
    }
}

TestSingleton.java:

@Singleton
@Startup
public class TestSingleton {

    @Inject
    private BeanInterface beanInterface;

    @PostConstruct
    public void init() {
        this.beanInterface.work();
    }
}

Packaging these classes in a war (with a web.xml) and deploying on wildfly, the implementation 1 is always injected in the Stateless bean.

Wildfly 10.1.0 uses weld-2.3.SP2 which implements CDI 1.2.

Thanks,

Charly


Solution

  • Although it does not make the @Specializes annotation work as expected, this solution suggested by John Ament allows to inject the second Implementation.

    Just change the @javax.enterprise.inject.Specializes annotation with @javax.annotation.Priority (and some value):

    @Dependent
    @Alternative
    @Priority(100)
    public class Implementation2 extends Implementation1 {
        @Override
        public void work() {
            System.out.println("test 2");
        }
    }
    

    Also missing in the OP question was the beans.xml (not web.xml) packaged in the WEB-INF:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
                          http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
        bean-discovery-mode="all">
    </beans>