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 />

context = new ClassPathXmlApplicationContext("META-INF/spring/<br />

mydocuments-resource-injection-context.xml");<br />

}<br />

}<br />

@Test<br />

public void testMenu() {<br />

log.debug("Calling the Menu as Resource Injection:");<br />

Menu menu = context.getBean(Menu.class);<br />

assertNotNull(menu);<br />

menu.printMenu();<br />

}<br />

You defined the Menu class and you added the Resource property (see Listing 6-3) that will be injected by the<br />

<strong>Spring</strong> container. One of the important things to mention here is that the <strong>Spring</strong> <strong>Framework</strong> will understand that by<br />

setting the property menuFile in the XML configuration (see Listing 6-4) it will inject as a Resource class value.<br />

In Listing 6-5 you added the testMenu method that will call your bean “menu” and it will print the contents of the<br />

menu.txt file.<br />

If you run your unit test with<br />

gradle :ch06:test<br />

you should have the following result:<br />

2014-02-16 11:00:46,377 DEBUG [main] Calling the Menu as Resource Injection:<br />

Welcome to My Documents<br />

1. Show all Documents<br />

2. Show all Document's Types<br />

3. Search by Type<br />

4. Quit<br />

Now, what would happen if you want to load the resource dynamically? Maybe you want to change the menu<br />

at runtime. Perhaps you have an application that needs to change some values, like some stock market values and<br />

definitions. You don’t want to stop your application, do the modification, and then redeploy, right? You want to<br />

actually make the new changes once you save the resource. The <strong>Spring</strong> <strong>Framework</strong> also provides a ResourceLoader<br />

class if you want to load some resource and change them based on a business rule. Listing 6-6 shows how to use it.<br />

Listing 6-6. ResourceLoaderMenu.java<br />

package com.apress.isf.spring.views;<br />

import static java.lang.System.out;<br />

import java.io.IOException;<br />

import java.io.InputStream;<br />

import java.util.Scanner;<br />

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

import org.springframework.core.io.ResourceLoader;<br />

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

65

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

Saved successfully!

Ooh no, something went wrong!