Here is what i have right now which works fine. All it does is a market class which returns an array of items objects:
I have class market
class market {
public ArrayList<Items> createItems(HashMap<String,String> map) {
ArrayList<Items> array = new ArrayList<Items>();
for (Map.Entry<String, String> m : map.entrySet()) {
Item item = new Item();
item.setName(m.key());
item.setValue(m.value());
array.add(item);
}
return array;
}
}
class Item is simple class with getter and setter for name and value
Here is how my config file looks:
@Configuration
public class MarketConfig {
@Bean
public Market market() {
return new Market();
}
}
How I want to change my code:( REASON: i dont want
Item item = new Item();
in then method. I want Spring to inject it into Market)
class market {
public Item item;
//getters and setters for item
public ArrayList<Items> createItems(HashMap<String,String> map) {
ArrayList<Items> array = new ArrayList<Items>();
for (Map.Entry<String, String> m : map.entrySet()) {
item.setName(m.key());
item.setValue(m.value());
array.add(item);
}
return array;
}
}
@Configuration
public class MarketConfig {
@Bean
@Scope("prototype")
public Item item() {
return new Item();
}
@Bean
public Market market() {
Market bean = new Market();
bean.setItem(item());
}
}
I know that prototype scope will give me new bean each time i call item();
Now i want new bean for each iteration in the for loop of createItems method. How can i tell spring to give me.
One way i know is Do
applicationContext context = new AnnotationConfigApplicationContext();
context.getBean(Item.class);
But is there any other way to get my work done.
Thanks
Yes, you can create prototype method on demand using look-up method
now in applicationContext.xml just put the following:
and configure factory:
Now all that you need to do in order to use it is Autowire it inside any bean:
and call yout look-up method:
each time you call
createItem()you will receive the reference to newly created instance of Item class.P.S: I see that you are using
@Configurationinstead of xml you need check if look-up method can be configured inside configuration bean.Hope it helps.
Update: The trick is simple: