Java Reference
In-Depth Information
Then you declare some product beans and a shopping cart bean in the IoC container as usual:
<beans ...>
<bean id="aaa" class="com.apress.springenterpriserecipes.shop.Battery">
<property name="name" value="AAA" />
<property name="price" value="2.5" />
</bean>
<bean id="cdrw" class="com.apress.springenterpriserecipes.shop.Disc">
<property name="name" value="CD-RW" />
<property name="price" value="1.5" />
</bean>
<bean id="dvdrw" class="com.apress.springenterpriserecipes.shop.Disc">
<property name="name" value="DVD-RW" />
<property name="price" value="3.0" />
</bean>
<bean id="shoppingCart" class="com.apress.springenterpriserecipes.shop.
ShoppingCart" />
</beans>
In the following Main class, you can test your shopping cart by adding some products to it. Suppose
that there are two customers navigating in your shop at the same time. The first one gets a shopping cart
by the getBean() method and adds two products to it. Then the second customer also gets a shopping
cart by the getBean() method and adds another product to it.
package com.apress.springenterpriserecipes.shop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
Product aaa = (Product) context.getBean("aaa");
Product cdrw = (Product) context.getBean("cdrw");
Product dvdrw = (Product) context.getBean("dvdrw");
ShoppingCart cart1 = (ShoppingCart) context.getBean("shoppingCart");
cart1.addItem(aaa);
cart1.addItem(cdrw);
System.out.println("Shopping cart 1 contains " + cart1.getItems());
ShoppingCart cart2 = (ShoppingCart) context.getBean("shoppingCart");
cart2.addItem(dvdrw);
System.out.println("Shopping cart 2 contains " + cart2.getItems());
}
}
Search WWH ::




Custom Search