My understanding of an alternative is that it's an alternative to some other implementation of an interface that you can use in a different deployment environment (e.g. a testing environment). An alternative bean is declared by annotating it with @Alternative
.
To use an alternative in a given deployment scenario, you select it in the <alternatives>
element of your CDI deployment descriptor META-INF/beans.xml
. This will enable @Alternative
beans which are disables by default.
When enabled, if the container finds an ambiguous dependency for a given injection point, it will look at alternatives that could be injected and, if there is exactly one, pick up this alternative.
In other words, alternatives are a nice way to replace an existing implementation with another one at deployment time. If there is nothing to replace, you don't need alternatives, just put your jar on the class path. Not sure this was exactly your question though, I have a doubt about the concept of 3rd-party jars.
More in 2.1.4. Alternatives, 4.6. Alternatives and 4.7. Fixing unsatisfied and ambiguous dependencies (but I guess that this is what you're reading).
Update: To answer your additional question.
If not, how to use beans from 3rd party libraries that don't have beans.xml
This can't happen, a bean archive must have a bean.xml
(be it empty) as detailed in the section 15.6. Packaging and deployment of the documentation:
CDI doesn't define any special
deployment archive. You can package
beans in JARs, EJB-JARs or WARs—any
deployment location in the application
classpath. However, the archive must
be a "bean archive". That means each
archive that contains beans must
include a file named beans.xml
in the
META-INF
directory of the classpath or
WEB-INF
directory of the web root (for
WAR archives). The file may be empty.
Beans deployed in archives that do not
have a beans.xml
file will not be
available for use in the application.
Then, to fix an unsatisfied and ambiguous dependency, refer to the section 4.7 previously mentioned.
Update 2: It appears that using BeforeBeanDiscovery.addAnnotatedType()
it is possible to add other classes to be taken into consideration during bean discovery. (BeforeBeanDiscovery
is an event)