Fabio Cepeda

Spring 2.5 – Loading files from service classes.

Posted on: November 6, 2008

Aware of the application context in the service layer.

Last night, I spent a few hours understanding how to load a file from a class in the service layer of my webapp that did not have access to the application context. I started using DefaultResourceLoader class to load the file with:

DefaultResourceLoader loader = new DefaultResourceLoader();
File file = loader.getResource(“file:”+filePath).getFile();

It worked on my windows environment, but when tested on Ubuntu it trhew an FileNotFoundException, the reason for this was that the ClassLoader used by the DefaultResorceLoader default constructor is the ClassLoader of the current Thread so the initial path was somewhere in /etc/init.d/, I tried using different prefixes without good results.

After investigating about Resources in the Spring Documentation I found that most of the resources are easily resolved when you have access to the aplication context, so I look how the form controllers had this access and found this useful class: ApplicationObjectSupport

Therefore, I had my class extend ApplicationObjectSupport and I was able to load the file using:

ApplicationContext ctx = getApplicationContext();
File file = ctx.getResource(xslPath).getFile();

The xslPath being something like WEB-INF/xsl/test.xsl

Some questions after this:

1. Is expensive to call the getApplicationContext()?
2. What class loader can be used for DefaultResourceLoader so that the file can be loaded?

Cheers,

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: