Ok so now how can we use CDI to solve the tight dependency with the EJBs ?

First approacht: using Qualifiers to solve the dependency at injection point.
The CDI specification (JSR-299) defines "Qualifer" as a means to uniquely identify one of the multiple implementations of the bean type to be injected. The spec defines certain built-in qualifiers (@Default, @Any, @Named, @New) and new qualifiers can be easily defined as well.

In this example we will define the Qualifier "MyCache" which will be used to select the bean implementation an injection point:

    
package com.packtpub.chapter4.qualifier;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.METHOD;
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({METHOD, FIELD, PARAMETER, TYPE})
public @interface MyCache {
}


Now all we need to do, is selecting the EJB implementation by adding the @MyCache annotation on the top of the EJB. For example, supposing we want to switch to the SingletonBeanMemory:
    
@Singleton
@MyCache
public class SingletonBeanMemory implements SingletonBean   {
 . . . . .
}

On the other hand, this dependency need to be injected in the PropertyManager Bean used by JSF:
    
public class PropertyManager implements Serializable {

 @Inject @MyCache
 SingletonBean ejb;
 @PostConstruct
 public void init() {
   // Removed tight dependency here
 }

That's all. The following picture resumes the Class diagram for this use case:


cdi jboss weld tutorial qualifier

 

0
0
0
s2smodern