Java Reference
In-Depth Information
<bean name="carService"
class="com.apress.simpleapp.service.CatServiceImpl" />
</beans>
Now that I have wired the bean in the XML configuration file, it is time to start the
IOC container, as shown in Listing 2-6.
Listing 2-6. SpringInitializer.java
Resource res = new FileSystemResource("spring-config.xml");
BeanFactory factory = new XmlBeanFactory(res);
Because I have the Spring container up and running, it is now possible to retrieve
beans from the bean factory that can then be used to perform some useful work in the
application.
Listing 2-7 is an example of pull DI with the Spring Framework. The application code
uses the Spring bean factory or IOC container to retrieve the car service objects using the
specified key. It is also evident from Listing 2-6 that it is possible to support several vari-
ants of CarSevice depending on the type of the car. This is because each car is different
and provides a different set of features and options. However, it is cumbersome to invoke
the getBean method each time you need a bean. It's as good as having the factory method
implementation of the pull DI I explained earlier with the example of a Car object.
Listing 2-7. CarServiceLocator.java
CarService service = (CarService) factory.getBean("carService");
One major goal of Spring is to be unobtrusive and impose minimal dependency on
the framework. This is achieved through different forms of push DI supported by the
Spring IOC container.
Setter Injection
In this mode of push DI, an object is created in the Spring IOC container by invoking the
zero-argument constructor. The dependent object is then passed as a parameter to the
setter method. The CarService object needs data access objects (DAO) to execute data-
base operations. The data access objects are injected via setter methods, as shown in
Listing 2-8.
 
Search WWH ::




Custom Search