How to specify an @Alternative producer method in beans.xml?
Asked Answered
Y

2

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?

Yahweh answered 3/2, 2014 at 8:17 Comment(0)
Y
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>
Yahweh answered 3/2, 2014 at 10:4 Comment(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.Ophiolatry
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.Escurial
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.Escurial
S
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

Stoichiometry answered 14/12, 2020 at 9:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.