Java Platform, Enterprise Edition (Java EE) 8
The Java EE Tutorial

Previous Next Contents

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, then 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, then 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();

Previous Next Contents
Oracle Logo  Copyright © 2017, Oracle and/or its affiliates. All rights reserved.