Introduction
In this chapter we will look at another really useful feature from the Java Spring framework. There are occasions when you want to perform some initialization tasks in your class before the instance of it is ready to be consumed or used by anyone and also cleanup the resources of that class when done using it; as in:
- public class Juggler implements Performer
- {
- private int _ballCount = 5;
- public Juggler() {}
- public Juggler(int ballCount)
- {
- _ballCount = ballCount;
- }
- public void Initialize()
- {
- System.out.println("Juggler: Registering in the show.");
- }
- public void Destroy()
- {
- System.out.println("Juggler: Signing off from the show.");
- }
- @Override
- public void Perform() throws PerformaceException
- {
- System.out.println("JUGGLING " + _ballCount + " BALLS");
- }
- }
So as you notice, before any performer in the show can perform, he needs to register into the show, so that is the first most important task that he should do before he can show his talent.
- <bean id="mike" class="spring.decoded.big.awards.Juggler" init-method="Initialize" destroy-method="Destroy">
- <constructor-arg value="10" />
- </bean>
- public static void main(String[] args) throws PerformaceException
- {
- System.out.println("Starting the show....");
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/decoded/big/awards/big-awards.xml");
- Performer performer = (Performer) context.getBean("mike");
- if (!PrePerformaceChecks(performer, "Mike"))
- return;
- performer.Perform();
- System.out.println("\nMoving onto the next performance");
- performer = (Performer) context.getBean("john");
- if (!PrePerformaceChecks(performer, "John"))
- return;
- performer.Perform();
- System.out.println("\nMoving onto the next performance");
- performer = (Performer) context.getBean("shaun");
- if (!PrePerformaceChecks(performer, "Shaun"))
- return;
- performer.Perform();
- System.out.println("\nShow is over.");
- context.close();
- }
Notice the context.close() call which would invoke the destroy-method on all the beans specified in our bean declaration file and perform the cleanup task, now if you run the application:
Notice the initialization stuff happening in the beginning, and the cleanup being performed in the end, the hefty job being delegated to Spring with just little or no effort.


Comments
Join the conversation! Your thoughts help the community grow.