Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Greenhorn
Posts: 10
Netbeans IDE VI Editor PHP
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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-

 
This is awkward. I've grown a second evil head. I'm going to need a machete and a tiny ad ...
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic