Reputation: 1423
I am working on a shopping-cart application
I have created one product bean and all the new products are being added through spring context given below
<bean id="product1" class="entities.Product">
<property name="name" value="product1" />
</bean>
<bean id="product2" class="entities.Product">
<property name="name" value="product2" />
</bean>
.....
My product team is adding one bean in the spring context every-time they have a new product
I am getting the bean using the following code
Product product = (Product) context.getBean("product1");
Product product2 = (Product) context.getBean("product2");
but every time they add the product I need to change my code to my display product set
How can I automate so that I can know number of product in the XML before hand or have every new product handled automatically
I am using this currently which is working fine but I am sure there is better solution to it
Set<Product> products = new HashSet<Product>();
int i=1;
while(true){
try{
products.add((Product) context.getBean("product"+i));
}
catch(NoSuchBeanDefinitionException n){
System.out.println(n);
break;
}
i++;
}
for(Product p : products)
System.out.println(p.getName());
Upvotes: 0
Views: 115
Reputation: 124506
You can use dependency injection for that. In your class where you need to Product
instances simple put a field which is a collection (List<Product>
, Set<Product>
or Map<String,Product>
) or an array (Product[]
and put @Autowired
or @Inject
on that field.
public MyClass {
@Autowired
private List<Product> products;
}
This will instruct the application context to inject all beans of the type Product
into that collection. Now in the method where you need it you can simply access the collection.
As explained here in the reference guide.
Upvotes: 0
Reputation: 52368
Use, instead, getBeansOfType() method that returns a Map: the key is the name of the bean, the value is the bean instance:
Map map = context.getBeansOfType(Product.class);
for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
String beanName = (String) iterator.next();
System.out.println(beanName + " for bean instance: " + map.get(beanName));
}
Upvotes: 1
Reputation: 3078
You can use context.getBeanNamesForType(Product.class)
to get the names of beans of specified type.
eg:
String names[] = context.getBeanNamesForType(Product.class);
for(int i=0;i<names.length;i++)
products.add((Product) context.getBean(names[i]));
More on getBeanNamesForType
Upvotes: 4