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 6 ■ Using Resource Files<br />

@Component("menu")<br />

public class ResourceLoaderMenu {<br />

@Autowired<br />

private ResourceLoader resourceLoader;<br />

}<br />

public void printMenu(String menuFile){<br />

try{<br />

InputStream stream = resourceLoader.getResource(menuFile).getInputStream();<br />

Scanner scanner = new Scanner(stream);<br />

while (scanner.hasNext()) {<br />

out.println(scanner.nextLine());<br />

}<br />

scanner.close();<br />

stream.close();<br />

}catch(IOException e){<br />

e.printStackTrace();<br />

}<br />

}<br />

Listing 6-6 shows the usage of the org.springframework.core.io.ResourceLoader class, and also the<br />

@Autowired annotation that will be instantiated by the <strong>Spring</strong> container and get it ready for when it is being used,<br />

like in the printMenu method. Next, let’s see Listing 6-7, your XML configuration, and Listing 6-8, your unit test.<br />

Listing 6-7. mydocuments-resourceloader-injection=context.xml<br />

<br />

<br />

<br />

<br />

<br />

Listing 6-7 only shows the tag that will tell the <strong>Spring</strong> container to look for<br />

annotated code and identify all the classes and instances to create.<br />

Listing 6-8 shows your unit test, and how you can load your menu.txt file. As you can see, you have several<br />

options for resource files. Running your unit test with<br />

gradle :ch06:test<br />

66

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

Saved successfully!

Ooh no, something went wrong!