Rapidpm Cdi Contextresolver 2.0

What is the ContextResolver Pattern?
It is a pattern described by Sven Ruppert (here) to solve the following problem.

The Problem
A service has several implementations which are provided to clients depending on a specific environment context (for example: test- or developmentcontext) on the service side. The client does not know about the context and the environment context must be dynamically configurable.

The Solution
Decouple the service creation from the context resolving by introducing

With that you can develop very flexible and extendable modules or applications which can be dynamically configured at runtime.

The Evolution
The previous version is implemented with CDI extensions which is a little bit harder to understand and needs a javax.enterprise.inject.spi.Extension file. So here is the improved version which uses only plain CDI-Producers and therefore should be easier to understand.

The client:

1 @Inject
2 @DemoLogicContext
3 Instance<DemoLogic> demoLogicInst;


The producer:

1 public class DemoLogicProducer
2 {
3  @Produces
4  @DemoLogicContext
5  public DemoLogic create(BeanManager beanManager, @Any Instance<ContextResolver> contextResolvers)
6  {
7   return ManagedBeanCreator.createManagedInstance(beanManager, contextResolvers, DemoLogic.class);
8  }
9 }


The ContextResolver:

 1 public class DemoLogicContextResolver implements ContextResolver
 2 {
 3  @Inject
 4  Context context;
 5  @Override
 6  public AnnotationLiteral<?> resolveContext(Class<?> targetClass)
 7  {
 8   //Determines the context and returns annotionliteral 
 9   return context.isUseB() ? new MandantB.Literal() : new MandantA.Literal();
10  }
11 }


The ManagedBeanCreator:

 1 public class ManagedBeanCreator
 2 {
 3  public static <T> T createManagedInstance(BeanManager beanManager, Instance<ContextResolver> contextResolvers,
 4    Class<? extends T> clazz)
 5  {
 6   //FindFirst
 7   for (ContextResolver contextResolver : contextResolvers)
 8   {
 9    AnnotationLiteral<?> annotationLiteral = contextResolver.resolveContext(DemoLogic.class);
10    Set<Bean<?>> beans = beanManager.getBeans(clazz, annotationLiteral);
11    //
12    //Create CDI Managed Bean
13    Bean<?> bean = beans.iterator().next();
14    CreationalContext<?> ctx = beanManager.createCreationalContext(bean);
15    return (T) beanManager.getReference(bean, clazz, ctx);
16   }
17   return null;
18  }
19 }
The sources can be found
<a href="https://bitbucket.org/abischof/cdicontextresolver2">here</a>.

Have fun coding.