216 CHAPTER 5: Building Java Web Applications with Spring Web MVC
- public void driver() {
- System.out.println(vehicle.drive());
- }
- }
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
- package com.apress.decoupled;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class VehicleApp {
- public static void main(String[] args) {
- ApplicationContext context = new ClassPathXmlApplicationContext(
- "beans.xml");
- VehicleService contestService = (VehicleService) context
- .getBean("vehicleService");
- contestService.driver();
- }
- }
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
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">