Java Reference
In-Depth Information
As a result of the preceding bean declaration, you can see that the two customers get the same
shopping cart instance.
Shopping cart 1 contains [AAA 2.5, CD-RW 1.5]
Shopping cart 2 contains [AAA 2.5, CD-RW 1.5, DVD-RW 3.0]
This is because Spring's default bean scope is singleton , which means Spring creates exactly one
shopping cart instance per IoC container.
<bean id="shoppingCart"
class="com.apress.springenterpriserecipes.shop.ShoppingCart"
scope="singleton" />
In your shop application, you expect each customer to get a different shopping cart instance
when the getBean() method is called. To ensure this behavior, you should change the scope of the
shoppingCart bean to prototype . Then Spring will create a new bean instance for each getBean()
method call and reference from the other bean.
<bean id="shoppingCart"
class="com.apress.springenterpriserecipes.shop.ShoppingCart"
scope="prototype" />
Now if you run the Main class again, you can see that the two customers get a different shopping cart
instance.
Shopping cart 1 contains [AAA 2.5, CD-RW 1.5]
Shopping cart 2 contains [DVD-RW 3.0]
1-7. Customizing Bean Initialization and Destruction
Problem
Many real-world components have to perform certain types of initialization tasks before they are ready
to be used. Such tasks include opening a file, opening a network/database connection, allocating
memory, and so on. Also, they have to perform the corresponding destruction tasks at the end of their
life cycle. So, you have a need to customize bean initialization and destruction in the Spring IoC
container.
Solution
In addition to bean registration, the Spring IoC container is also responsible for managing the life cycle
of your beans, and it allows you to perform custom tasks at particular points of their life cycle. Your tasks
should be encapsulated in callback methods for the Spring IoC container to call at a suitable time.
 
 
Search WWH ::




Custom Search