- Spring 5.0 Cookbook
- Sherwin John Calleja Tragura
- 319字
- 2021-07-08 10:16:14
How it works...
The principle behind creating <bean> objects in the container is called the Inversion of Control design pattern. In order to use objects, their dependencies and also their behaviors, these must be placed within the framework per se. After registering them in the container, Spring will just take care of their instantiation and their availability to other objects. Developer can just fetch them if they want to include them in their software modules, as shown in the following diagram:
The IoC design pattern can be synonymous with the Hollywood Principle (Don't call us, we'll call you!), which is a popular line in most object-oriented programming languages. The framework does not care whether the developer needs the objects or not because the lifespan of the objects lies on the framework's rules.
In the case of setting new values or updating values of an object's private variables, IoC has an implementation that can be used for "injecting" new actual values or object references to <bean> and it is popularly known as the Dependency Injection (DI) design pattern. This principle exposes all the <bean> to the public through its setter methods or the constructors. Injecting Spring values and object references to the method signature using the <property> tag without knowing its implementation is called the Method Injection type of DI. On the other hand, if we create the bean with initialized values injected to its constructor through <constructor-arg>, it is known as Constructor Injection.
To create the ApplicationContext container, we need to instantiate ClassPathXmlApplicationContext or FileSystemApplicationContext, depending on the location of the XML definition file. Since the file is found in ch02-xml\src\main\java\, ClassPathXmlApplicationContext implementation is the best option because everything in src is compiled and deployed to the classes folder of the web project ch02-xml\WEB-INF. This proves that the ApplicationContext is an object too, bearing all those XML metadata. It has several overloaded getBean() methods used to fetch all the objects loaded with it.