Understanding the Bean Life Cycle and Used Patterns

In the previous chapter, you saw how Spring creates beans in the container. You also learned how to configure the dependency injection pattern using XML, Java, and Annotation. In this chapter, we will go into more detail, beyond injecting beans and the configuration of dependencies in a Spring application. Here, you will explore the life and scope of beans in the container, and learn how the Spring container works on the defined Spring bean configuration with XML, Annotation, and Java. Spring allows us to control not only the various configurations for the DI pattern and dependency values that are to be injected into the object created from a particular bean definition, but also the life and scope of the beans created from a particular bean definition.

When I was writing this chapter, my two and a half year old son, Arnav, came to me and started playing a video game on my mobile. He was wearing a T-Shirt, which had an interesting quote on it, and these lines described his whole day. The lines went like this--
My Perfect Day: Wake up, Play Video Games, Eat, Play Video Games, Eat, Play Video Games, and Sleep.

Actually, these lines perfectly reflected his life cycle for each day, as he woke up, played, ate, and played again before, finally, going to sleep. With this example, I just wanted to demonstrate that everything has a life cycle. We could discuss the life cycle of a butterfly, a star, a frog, or a plant. But let's talk about something more interesting--the life cycle of a bean!

Every bean in the Spring container has a life cycle and its own scope. The Spring container manages the life of the beans in a Spring application. We can customize it in some phases by using Spring-aware interfaces. This chapter will talk about the life of a bean in the container, and how it is managed using design patterns in the various phases of its life. By the end of this chapter, you would have a fair idea of the bean life cycle and its various phases in the container. You will also learn about the many types of bean scope in Spring. This chapter will cover the following points:

  • The Spring bean life cycle, and its phases, which are listed as follows:
    • The initialization phase
    • The Use phase
    • The destruction phase
  • Spring callbacks
  • Understanding bean scopes
    • Singleton pattern
    • Prototype pattern
    • Custom scopes
    • Other bean scopes

Now let's take a moment to see how Spring manages the life cycle of a bean from creation to destruction in the Spring application

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset