My JSF Books/Videos My JSF Tutorials OmniFaces/JSF PPTs
JSF 2.3 Tutorial
JSF Caching Tutorial
JSF Navigation Tutorial
JSF Scopes Tutorial
JSF Page Author Beginner's Guide
OmniFaces 2.3 Tutorial Examples
OmniFaces 2.2 Tutorial Examples
JSF Events Tutorial
OmniFaces Callbacks Usages
JSF State Tutorial
JSF and Design Patterns
JSF 2.3 New Features (2.3-m04)
Introduction to OmniFaces
25+ Reasons to use OmniFaces in JSF
OmniFaces Validators
OmniFaces Converters
JSF Design Patterns
Mastering OmniFaces
Reusable and less-verbose JSF code

My JSF Resources ...

Java EE Guardian
Member of JCG Program
Member MVB DZone
Blog curated on ZEEF
OmniFaces is an utility library for JSF, including PrimeFaces, RichFaces, ICEfaces ...

[OmniFaces Utilities] - Find the right JSF OmniFaces 2 utilities methods/functions

Search on blog

Petition by Java EE Guardians


marți, 21 iunie 2016

CDI-JSF: Using CDI alternatives priority (@Priority)

So, since you are familiar with the above post, now let's suppose that we have multiple mock implementations. In such cases, the problem is how to instruct the container to choose between the implementations? The answer relies on alternatives priority!

Basically, we annotate each mock implementation with @Priority and provide a number as the level of priority. The higher number has the higher priority. Here it is three mock implementations with priorities 1,2 and 3:

public class FooServiceMock implements IFooService {

 public List getAllFoo() {
  return Arrays.asList("foo 1", "foo 2", "foo 3");

public class BestFooServiceMock implements IFooService {

 public List getAllFoo() {
  return Arrays.asList("best foo 1", "best foo 2", "best foo 3");

public class GreatFooServiceMock implements IFooService {

 public List getAllFoo() {
  return Arrays.asList("great foo 1", "great foo 2", "great foo 3");

The mock implementation annotated with @Priority(3) has the higher priority. When we run the below code CDI will automatically choose the GreatFooServiceMock:

public class FooBean {

 private static final Logger LOG = Logger.getLogger(FooBean.class.getName());

 private IFooService fooService; // choose GreatFooServiceMock

 public void loadAllFoo() {
  List allfoo = fooService.getAllFoo();

  LOG.log(Level.INFO, "allfoo:{0}", allfoo);

Now, we can also write a test using CDI-Unit as below (this will also choose the GreatFooServiceMock):

@ActivatedAlternatives({FooServiceMock.class, BestFooServiceMock.class, GreatFooServiceMock.class})
public class FooBeanTest {
 FooBean fooBean;

 public void testStart() {

We can use the @Priority annotation to specify alternatives globally for an application that consists of multiple modules like this:

public class ...

The complete example is available here.

Niciun comentariu :

Trimiteți un comentariu


Postări populare

Follow by Email

Visitors Starting 4 September 2015

Locations of Site Visitors