25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 2 ■ Working with Classes and Dependencies<br />

com.apress.isf.java.test.MyDocumentsTest > testListAll STARTED<br />

com.apress.isf.java.test.MyDocumentsTest > testListAll PASSED<br />

BUILD SUCCESSFUL<br />

Total time: 12.039 secs<br />

■ ■Note The above output shows all the tests in this chapter. You can run from the base project with the following<br />

command: $ gradle :ch02:test<br />

Using the <strong>Spring</strong> <strong>Framework</strong><br />

As you can see, you started with a simple Java application, and a clean design using interfaces that will promote<br />

decoupling and will not depend on a specific implementation because it follows a contract. But there is still some<br />

code that you need to refactor in your unit test. Listing 2-5 shows that you need to instantiate a new MySearchEngine<br />

class, but what happens if you need to add a different implementation? Well, just change the name, and recompile<br />

and rerun to test it, right? Or maybe you need to instantiate more of these classes somewhere; it will be some hard<br />

work! That’s why you need some kind of dependency mechanism tool to avoid this hassle. In other words, you need a<br />

way to create this dependency dynamically and avoid instantiating a class every time you add a new implementation.<br />

The <strong>Spring</strong> <strong>Framework</strong>’s primary goal is to offer a dependency injection container that will facilitate the creation<br />

of instances and interaction between objects. But how are you going to use the <strong>Spring</strong> <strong>Framework</strong>? And what is the<br />

dependency injection thing? Or the <strong>Spring</strong> container? Well, let’s start coding and answer your questions.<br />

You are going to create the file shown in Listing 2-7. If you are using the book’s companion source code, you can<br />

find it at /ch02/src/test/resources/META-INF/spring.<br />

Listing 2-7. mydocuments-context.xml<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

Listing 2-7 shows an XML file. This file is the configuration that the <strong>Spring</strong> <strong>Framework</strong> needs to know in order to<br />

inject the dependencies and the interaction between objects. The main tag, , uses XML namespaces to give<br />

your file the correct syntax and usage; and it can contain one or more children. In this case, it uses another tag, .<br />

This is the key to define the dependency; here you are creating an “engine” bean that points to an implementation.<br />

19

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!