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 3 ■ Applying Different Configurations<br />

In Listing 3-7, in your setup() method (this method will run before each method in this class gets executed), you<br />

are using the ClassPathXmlApplicationContext class that will run your <strong>Spring</strong> container by creating and wiring up<br />

all the instances and having them ready when you need them.<br />

Now let’s run the unit test (see Listing 3-7) with the following command:<br />

gradle test<br />

Or if you are on the project’s base path, you can run it with<br />

gradle :ch03:test<br />

■ ■Note Every chapter will contain several unit test files, so the following command will run a specific test:<br />

gradle –Dtest.single=MyDocumentsTest test<br />

So far you have seen how to configure the <strong>Spring</strong> container by adding beans and referencing them so the<br />

container knows about the creation and relationship, and gets them ready when you need them. Also, remember that<br />

the <strong>Spring</strong> <strong>Framework</strong> allows you to have different configurations apart from the XML, so in the next section you are<br />

going to see how to use annotations to accomplish the same configuration.<br />

Using <strong>Spring</strong> Annotations<br />

Java annotations were introduced in Java 5, and they added a great value to the Java language because you can add<br />

metadata to a class that can be used at compile time and at runtime, making new ways to develop. The <strong>Spring</strong> team<br />

took advantage of this new feature to provide a <strong>Spring</strong> annotation-based configuration. This feature was introduced in<br />

version 2.5.<br />

But enough talk, let’s go to the code and see what you are going to change in order to use the <strong>Spring</strong> annotation<br />

configuration. See Listing 3-8.<br />

Listing 3-8. AnnotatedSearchEngine.java<br />

package com.apress.isf.spring.annotated.service;<br />

import java.util.ArrayList;<br />

import java.util.Arrays;<br />

import java.util.List;<br />

import org.springframework.beans.factory.annotation.Autowired;<br />

import org.springframework.stereotype.Service;<br />

import com.apress.isf.java.model.Document;<br />

import com.apress.isf.java.model.Type;<br />

import com.apress.isf.java.service.SearchEngine;<br />

import com.apress.isf.spring.data.DocumentDAO;<br />

@Service("engine")<br />

public class AnnotatedSearchEngine implements SearchEngine {<br />

33

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

Saved successfully!

Ooh no, something went wrong!