Question

Say I have:

public interface Foo {...}

public class AltProducer {
  private Foo altFoo;

  @Produces @Alternative
  public Foo getAltFoo() { return altFoo; }
}

What do I need to put in beans.xml so that my AltProducer's @Produces method will get called, instead of injecting Bar?

Was it helpful?

Solution

Found it - you can just specify the whole producer class as an alternative.

@Alternative
public class AltProducer { ... }

beans.xml:

<beans>
  <alternatives>
    <class>com.package.AltProducer</class>
  </alternatives>
</beans>

OTHER TIPS

you have to create a beans.xml file in src/main/resources/META-INF and then

<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">
<beans>
  <alternatives>
    <class>com.package.AltProducer</class>
  </alternatives>
</beans>
</beans>

and don't forget to annotate your class with @alternative you can check this article about cdi https://www.baeldung.com/java-ee-cdi

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top