我正在开发购物车应用程序
我创建了一个产品 bean,所有新产品都通过 spring 上下文添加 下面给出
<bean id="product1" class="entities.Product">
<property name="name" value="product1" />
</bean>
<bean id="product2" class="entities.Product">
<property name="name" value="product2" />
</bean>
.....
我的产品团队每次推出新产品时都会在 Spring 上下文中添加一个 Bean
我使用以下代码获取 bean
Product product = (Product) context.getBean("product1");
Product product2 = (Product) context.getBean("product2");
但每次他们添加产品时,我都需要将代码更改为我的显示产品集
如何实现自动化,以便我可以事先知道 XML 中的产品数量 或者自动处理每个新产品
我目前正在使用这个,它工作正常,但我确信有更好的解决方案
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());
最佳答案
您可以使用context.getBeanNamesForType(Product.class)
来获取指定类型的bean的名称。
例如:
String names[] = context.getBeanNamesForType(Product.class);
for(int i=0;i<names.length;i++)
products.add((Product) context.getBean(names[i]));
关于java - 自动将新的 Spring 启动的 Bean 添加到应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23539994/