Java Reference
In-Depth Information
10.
11. public void driver() {
12. System.out.println(vehicle.drive());
13.
14. }
15.
16. }
17.
Line 7 : In Listing 5-15, we have removed total control from the class
VehicleService and kept it in the XML configuration file, and the dependency is
being injected into the class VehicleService through a setter method on line 7.
Now create a client class VehicleApp , as illustrated in Listing 5-16.
Listing 5-16. Vehicle Application
1. package com.apress.decoupled;
2. import org.springframework.context.ApplicationContext;
3. import org.springframework.context.support.ClassPathXmlApplicationContext;
4.
5. public class VehicleApp {
6.
7. public static void main(String[] args) {
8. ApplicationContext context = new ClassPathXmlApplicationContext(
9. "beans.xml");
10. VehicleService contestService = (VehicleService) context
11. .getBean("vehicleService");
12. contestService.driver();
13. }
14.
15. }
Lines 8 to 9 : These lines instantiate the application context and pass the
configuration file.
Lines 10 to 11 : These lines get the bean from the configuration file. To get a
declared bean from a bean factory or an application context, you make a call to
the getBean() method, pass in the unique bean name, and cast the return type
to its actual type before using it.
Now, you need to create a bean configuration file, which is an XML file (as illustrated in Listing 5-17),
that connects the beans.
Listing 5-17. Configuration File
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans xmlns=" http://www.springframework.org/schema/beans "
3. xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "
4. xsi:schemaLocation=" http://www.springframework.org/schema/beans
5. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd " >
6. <bean id="car" class="com.apress.decoupled.Car" />
 
Search WWH ::




Custom Search