Pages

Showing posts with label ResourceLoader. Show all posts
Showing posts with label ResourceLoader. Show all posts

Tuesday, June 26, 2012

How to use Spring Resources in WAR Example

Problem: Assume you have a some resources in your WAR file, that you want to use in run time, for example accessing XML files and printing it's content, or reading some meta-data and using it.

Solution: Spring provided an useful Resource abstraction, that can be used. To obtain a reference to a service that will allow access to resource, you can use:

@Autowired
private ResourcePatternResolver resourceLoader = null;


Spring will inject a bean that implements this interface, in practice it would actually be a reference for ApplicationContext (ApplicationContext must implement ResourcePatternResolver interface)

and then you can get an array of resources by using:

Resource[] resources = resourceLoader.getResources("resources/my-xml-files/**");

After that, you can iterate over the resources and easily perform

resource.getInputStream()

to read the contents.

Good luck