2

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 ?

Community
  • 1
  • 1
user962206
  • 15,637
  • 61
  • 177
  • 270
  • 1
    Like I said in a comment in the question you linked, I fail to see why you should limit how you use Spring just to satisfy a strict interpretation of IoC. Spring is about more than just inversion of control. If using Spring as an object factory through `getBean()` works well in your design, then I don't see a problem. – pap Feb 20 '13 at 07:27

3 Answers3

1

You are looking for Lookup Method Injection.

see http://static.springsource.org/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-method-injection

Jose Luis Martin
  • 10,459
  • 1
  • 37
  • 38
0

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
    }
 }

}
NPKR
  • 5,368
  • 4
  • 31
  • 48
0

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" /> 
Nikita Bosik
  • 851
  • 1
  • 14
  • 20
othman
  • 4,428
  • 6
  • 34
  • 45
  • see spring documentation. look for factory-method section 3.3.2.3 Instantiation using an instance factory method: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html – othman Feb 20 '13 at 05:47