Java Reference
In-Depth Information
Resource is a general interface in Spring for representing an external resource. Spring provides
several implementations for the Resource interface. The resource loader's getResource() method will
decide which Resource implementation to instantiate according to the resource path.
How It Works
Suppose you want to display a banner at the startup of your shop application. The banner is made up of
the following characters and stored in a text file called banner.txt . This file can be put in the current
path of your application.
*************************
* Welcome to My Shop! *
*************************
Next you have to write the BannerLoader class to load the banner and output it to the console.
Because it requires access to a resource loader for loading the resource, it has to implement either the
ApplicationContextAware interface or the ResourceLoaderAware interface.
package com.apress.springenterpriserecipes.shop;
...
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
public class BannerLoader implements ResourceLoaderAware {
private ResourceLoader resourceLoader;
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public void showBanner() throws IOException {
Resource banner = resourceLoader.getResource(" file :banner.txt");
InputStream in = banner.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while (true) {
String line = reader.readLine();
if (line == null)
break;
System.out.println(line);
}
reader.close();
}
}
Search WWH ::




Custom Search