The Java EE 6 Tutorial

Injecting Objects by Using Producer Methods

Producer methods provide a way to inject objects that are not beans, objects whose values may vary at runtime, and objects that require custom initialization. For example, if you want to initialize a numeric value defined by a qualifier named @MaxNumber, you can define the value in a managed bean and then define a producer method, getMaxNumber, for it:

private int maxNumber = 100;
...
@Produces @MaxNumber int getMaxNumber() {
    return maxNumber;
}

When you inject the object in another managed bean, the container automatically invokes the producer method, initializing the value to 100:

@Inject @MaxNumber private int maxNumber;

If the value can vary at runtime, the process is slightly different. For example, the following code defines a producer method that generates a random number defined by a qualifier called @Random:

private java.util.Random random = 
    new java.util.Random( System.currentTimeMillis() );

java.util.Random getRandom() {
        return random;
}

@Produces @Random int next() {
    return getRandom().nextInt(maxNumber);
}

When you inject this object in another managed bean, you declare a contextual instance of the object:

@Inject @Random Instance<Integer> randomInt;

You then call the get method of the Instance:

this.number = randomInt.get();