Java Reference
In-Depth Information
Qualii ers
This section looks at how you would construct the qualii er classes.
In Listing 5‐12, you create a qualii er named Mongo that you can use to annotate i elds. If you want
to use this annotation on a METHOD , a PARAMETER , or a class/interface ( TYPE ), you can add it to the
@Target annotation.
LISTING 5‐12: Create a custom qualii er named @Mongo
package com.devchronicale.di;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
@Qualifier
@Retention(RUNTIME)
@Target({FIELD})
public @interface Mongo {}
The discussion regarding the varied use of annotations continues in more depth in Chapter 6.
Alternatives
In the examples so far, you learned how you can disambiguate between two distinct
implementations of the UserDataRepository interface by using qualii ers. You normally make this
choice of implementation at development time by changing the source code. However, you can also
make this choice at deployment time by using the @Alternative annotation and some coni guration
in the bean.xml deployment descriptor.
Adapting the examples so far, you annotate the two implementations of the UserDataRepository
interface with @Alternative and add some coni guration XML to the bean.xml i le. This is where
you decide which implementation to inject.
@Alternative
public class UserDataRepositoryMongo implements UserDataRepository {...}
@Alternative
public class UserDataRepositoryMySQL implements UserDataRepository {...}
The implementation that you use in the application is declared in the bean.xml i le:
<beans ...>
<alternatives>
<class> com.devchronicale.di.UserDataRepositoryMongo </class>
</alternatives>
</beans>
 
Search WWH ::




Custom Search