Java Reference
In-Depth Information
By calling the getResource() method from the application context, you can retrieve an external
resource specified by a resource path. Because your banner file is located in the file system, the resource
path should start with the file prefix. You can call the getInputStream() method to retrieve the input
stream for this resource. Then you read the file contents line by line with BufferedReader and output
them to the console.
Finally, you declare a BannerLoader instance in the bean configuration file to display the banner.
Because you want to show the banner at startup, you specify the showBanner() method as the
initialization method.
<bean id="bannerLoader"
class="com.apress.springenterpriserecipes.shop.BannerLoader"
init-method="showBanner" />
Resource Prefixes
The previous resource path specifies a resource in the relative path of the file system. You can specify an
absolute path as well.
file:c:/shop/banner.txt
When your resource is located in the classpath, you have to use the classpath prefix. If there's no
path information presented, it will be loaded from the root of the classpath.
classpath:banner.txt
If the resource is located in a particular package, you can specify the absolute path from the
classpath root.
classpath:com/apress/springenterpriserecipes/shop/banner.txt
Besides a file system path or the classpath, a resource can also be loaded by specifying a URL.
http://springenterpriserecipes.apress.com/shop/banner.txt
If there's no prefix presented in the resource path, the resource will be loaded from a location
according to the application context. For FileSystemXmlApplicationContext , the resource will be loaded
from the file system. For ClassPathXmlApplicationContext , it will be loaded from the classpath.
Injecting Resources
In addition to calling the getResource() method to load a resource explicitly, you can inject it by using a
setter method:
package com.apress.springenterpriserecipes.shop;
...
import org.springframework.core.io.Resource;
public class BannerLoader {
private Resource banner;
public void setBanner(Resource banner) {
this.banner = banner;
}
Search WWH ::




Custom Search