Spicy Spring: Create your own ResourceLoader

As a Spring developer we know how to load a resource in a Service. The prefixes of classpath: and file: are commonly used. But what if we want to load resources from a different location like a database table RESOURCE, with our own prefix db:?

The Spring Framework provides some default built-in resource implementations, which can be found in the chapter Resources in the Spring Framework Reference Guide. The URL is prefixed and handled by the corresponding ResourceLoader (JavaDoc).

If we want to load a resource from a database table RESOURCE we have to create our own ResourceLoader which triggers on the prefix db:.

DatabaseResourceDao

Let’s create an interface which describes the action of getting a resource based on the resourceName.

In this example our filename is equal to our resourcename. So if we execute getResource("db:myResource.txt") the name of the resource would be myResource.txt.

Database table

Next we create a database table which contains our binary resources. It has two columns: one for the name and one with the binary data.

DatabaseResourceDao implementation

After we have created our database table it is time to write a DatabaseResourceDao implementation to retrieve the Resource data from our database table.

A Custom ResourceLoader

We our able to retrieve a Resource with the created bean DatabaseResourceDaoImpl. This bean needs to be injected into a custom ResourceLoader, a standard Spring interface for loading a Resource.
Our DatabaseResourceLoader is an implementation that looks for “db:”. If the string parameter location contains the prefix db:, we know we need to load the resource by making a call to the DatabaseResourceDao implementation and returning the result. When the location parameter does not contain the “db:” prefix, the DatabaseResourceLoader will delegate to the delegate, which will be the original ResourceLoader.

NB. Our DatabaseResourceLoader isn’t ComponentScanned. In the next step we will construct it manually.

Activate the ResourceLoader

At last we need to construct and bind the DatabaseResourceLoader and inject the original ResourceLoader. By defining a bean that implements the BeanFactoryPostProcessor and the ResourceLoaderAware interface we get the original ResourceLoader injected and register the new one by calling beanFactory.registerResolvableDependency(..).
We also need to implement ApplicationContextAware to be able to inject the ApplicationContext into the DatabaseResourceLoader.
The BeanPostProcessor interface is implemented to make sure that every other bean that implements ResourceLoaderAware gets the correct ResourceLoader injected.

Use in our Service

Finally we are able to load a resource with db: as prefix.

One thought on “Spicy Spring: Create your own ResourceLoader

Leave a Reply

Your email address will not be published. Required fields are marked *