Learn Java for Web Development

(Tina Meador) #1

216 CHAPTER 5: Building Java Web Applications with Spring Web MVC







  1. public void driver() {

  2. System.out.println(vehicle.drive());



  3. }



  4. }




   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. public class VehicleApp {



  5. public static void main(String[] args) {

  6. ApplicationContext context = new ClassPathXmlApplicationContext(

  7. "beans.xml");

  8. VehicleService contestService = (VehicleService) context

  9. .getBean("vehicleService");

  10. contestService.driver();

  11. }



  12. }


   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">




Free download pdf