type=page
status=published
title=Injecting Objects by Using Producer Methods
next=cdi-basic013.html
prev=cdi-basic011.html
~~~~~~
= Injecting Objects by Using Producer Methods


[[GJDID]]

[[injecting-objects-by-using-producer-methods]]
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:

[source,oac_no_warn]
----
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:

[source,oac_no_warn]
----
@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`:

[source,oac_no_warn]
----
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:

[source,oac_no_warn]
----
@Inject @Random Instance<Integer> randomInt;
----

You then call the `get` method of the `Instance`:

[source,oac_no_warn]
----
this.number = randomInt.get();
----
