aspose file tools*
The moose likes EJB and other Java EE Technologies and the fly likes Under what circumstances do I need to use the @produces annotation? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "Under what circumstances do I need to use the @produces annotation?" Watch "Under what circumstances do I need to use the @produces annotation?" New topic
Author

Under what circumstances do I need to use the @produces annotation?

Oliver Chase
Greenhorn

Joined: Feb 09, 2010
Posts: 15
Hi, I do not understand the practical usage of the @Produces annotation.

@Produces
@Random
int next() {
// a number between 1 and 100
return getRandom().nextInt(maxNumber - 1) + 1;
}

@Produces
@MaxNumber
int getMaxNumber() {
return maxNumber;
}


taken from:
http://www.jboss.org/jdf/quickstarts/jboss-as-quickstart/guide/NumberguessQuickstart/#_the_numberguess_quickstart_in_depth


What is being produced and how does the container know to call a Producer method? I would never have thought that I need a @produces just to return an int.

Thanks
Alfred Swensen
Greenhorn

Joined: May 25, 2009
Posts: 10

Oliver Chase wrote:Hi, I do not understand the practical usage of the @Produces annotation.


Sometimes you want to use Dependency Injection like this:

class Foo {
@Inject
Integer someNumber;
...
}

That does, of course, not work because Java has no clue which Number to inject. It could try to call "new Integer()" but that does not work without a constructor parameter.
So you have to create a method that's annotated with @Produces and returns an Integer. Java scans for all @Produce methods and it's presence somewhere on the classpath is enough to let it be used for all Integers that should be injected.

Now the next problem is that you don't want random numbers for *every* variable that happens to be Integer. So you should somehow mark the producer by creating a new inteface with @Qualifier annotation and adding that interface name (@Random in your example) to both, the @Inject an the @Produce. Now Java can match that too and knows that you want the random number here.

bye,

-christian-

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Under what circumstances do I need to use the @produces annotation?