img
Figure 5-1. Spring beans life cycle
Hooking into Bean Creation
By being aware of when it is initialized, a bean can check to see whether all its required dependencies
are satisfied. Although Spring can check dependencies for you, it is pretty much an all-or-nothing
approach, and it doesn't offer any opportunities for applying additional logic to the dependency
resolution procedure. Consider a bean that has four dependencies declared as setters, two of which are
required and one of which has a suitable default in the event that no dependency is provided. Using an
initialization callback, your bean can check for the dependencies it requires, throwing an exception or
providing a default as needed.
A bean cannot perform these checks in its constructor because at this point, Spring has not had an
opportunity to provide values for the dependencies it can satisfy. The initialization callback in Spring is
called after Spring finishes providing the dependencies that it can and performs any dependency checks
that you ask of it.
You are not limited to using the initialization callback just to check dependencies; you can do
anything you want in the callback, but it is most useful for the purpose we have described. In many cases,
the initialization callback is also the place to trigger any actions that your bean must take automatically in
response to its configuration. For instance, if you build a bean to run scheduled tasks, the initialization
callback provides the ideal place to start the scheduler--after all, the configuration data is set on the bean.
Note You will not have to write a bean to run scheduled tasks because this is something Spring can do
automatically through its built-in scheduling feature or via integration with the Quartz scheduler. We cover this in
more detail in Chapter 15.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home