10

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?

2 Answers 2

16

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>
3
  • 3
    +1. I find it very cumbersome. Javadocs for @Alternative says: May be applied to a bean class, producer method or field . But it is misleading, because inside beans.xml we can only specify <class> or <stereotype> - there is no way to enter producer method or field.
    – G. Demecki
    Jul 9, 2016 at 7:47
  • You are exactly right. Having the @Alternative annotation in a producer method makes absolutely no sense because it the produced Alternative cannot be enabled in the beans.xml.
    – 99Sono
    Dec 9, 2016 at 10:23
  • Another point with CDI 1.1 is that in most cases, when you annoatate the parent class as an Alternative, you wll also want to add the Priority annotation to enable that alternative accross all BeanDeploymenyArchieves of WELD. So Remember, rarely do you use Alternative without Priority in jEE 7.
    – 99Sono
    Dec 9, 2016 at 10:25
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.