user962206
user962206

Reputation: 16117

Retrieving beans that are scope prototype using getBean

I have read here that using is considered applicationContext.getBean("somebeananmehere") is bad.

if that so, how would I programmatically get beans (depends on the user on what kind of bean he wants, let's say he can choose different grocery items eg apple,soap,detergent)?

let's say

switch(num){
  case 1 : myGrocery  = (GroceryItem) applicationContext.getBean("SOAP");break;
  case 2: myGrocery = (GroceryItem) applicationContext.getBean("APPLE");break;
  default:
   //more code here
}

this is what I am doing in my application where the user is selecting his or her grocery items. (This is a console application)

if applicationContext.getBean is considered bad, then what is the alternative ?

Upvotes: 2

Views: 5339

Answers (3)

othman
othman

Reputation: 4556

You can use spring's factory-method option. Just write your factory method to return the right class and in your xml beans:

<bean factory-method="your factory method name" class="your class" /> 

Upvotes: 0

NPKR
NPKR

Reputation: 5496

Check this

class Example {

  private SOAP soap;

  @Autowired
  public void setSoap(SOAP soap) {
    this.soap= soap;
  }

  private APPLE apple;

  @Autowired
  public void setApple(APPLE apple) {
    this.apple= apple;
  }


  public void yourMethod(int num) {
   switch(num){
    case 1 : myGrocery  = (GroceryItem) soap;break;
    case 2: myGrocery = (GroceryItem) apple;break;
    default:
     //more code here
    }
 }

}

Upvotes: 0

Related Questions