Search code examples
java-ee-6cdijboss-weldweld

CDI Producer(s) Different Versions of same class


I have a JEE6 simple producer class that produces a SimpleDateFromat object:

public class myProducer {

    @Produces public SimpleDateFormat produceASimpleDateFormat(final InjectionPoint injectionPoint)
    {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
}

I want to either:

  1. create a new producer and somehow be able to dictate in the class what DateFormat gets injected where or...
  2. edit my existing Producer to produce a different SimpleDateFormat based on a passed parameter.

How best should I achieve it?


Solution

  • Sounds like a use for qualifiers.

    You can either

    @Produces
    @TypeA
    public SimpleDateFormat produceTypeAFormat() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
    
    @Produces
    @TypeB
    public SimpleDateFormat produceTypeBFormat() {
        return new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
    }
    

    Or something more dynamic where you read the injection point to read the qualifier w/ a content, such as @Format("yyyy-MM-dd HH:mm:ss") where you can read the qualifier on the injectionpoint.