Fabio Cepeda

Posts Tagged ‘Spring

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?