Java Reference
In-Depth Information
Using Specialization
Specialization has a function similar to that of alternatives, in that it allows you to substi-
tute one bean for another. However, you might want to make one bean override the other
in all cases. Suppose you defined the following two beans:
@Default @Asynchronous
public class AsynchronousService implements Service { ... }
@Alternative
public class MockAsynchronousService extends AsynchronousService {
... }
If you then declared
MockAsynchronousService
as an alternative in your
beans.xml
file, the following injection point would resolve to
MockAsynchron-
ousService
:
@Inject Service service;
The following, however, would resolve to
AsynchronousService
rather than
MockAsynchronousService
, because
MockAsynchronousService
does not
have the
@Asynchronous
qualifier:
@Inject @Asynchronous Service service;
To make sure
MockAsynchronousService
was always injected, you would have to
implement all bean types and bean qualifiers of
AsynchronousService
. However,
if
AsynchronousService
declared a producer method or observer method, even this
cumbersome mechanism would not ensure that the other bean was never invoked. Spe-
cialization provides a simpler mechanism.
Specialization
happens at development time as well as at runtime. If you declare that one
bean specializes another, it extends the other bean class, and at runtime the specialized
bean completely replaces the other bean. If the first bean is produced by means of a pro-
ducer method, you must also override the producer method.
You specialize a bean by giving it the
javax.enterprise.inject.Specializes
annotation. For example, you might
declare a bean as follows: