Home  >  Spring Core

ResourceLoaderAware Spring Example

By Arvind Rai, August 17, 2013
org.springframework.context.ResourceLoaderAware is an interface. To create our own ResourceLoader, we need to create a class that will implement the interface ResourceLoaderAware. We will implement a method to get resource loader. Find the below example.

EntitlementService.java
package com.concretepage;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
public class EntitlementService implements ResourceLoaderAware {
	private ResourceLoader resourceLoader;
	public ResourceLoader getResourceLoader() {
		return resourceLoader;
	}
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}
	public Resource getResource(String path) {
		return this.getResourceLoader().getResource(path);
	}
}
 


SpringDemo.java
package com.concretepage;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
public class SpringDemo {
    public static void main(String... args) throws IOException {
    	ApplicationContext context = new ClassPathXmlApplicationContext("spring-app.xml");
    	EntitlementService entSer = (EntitlementService)context.getBean("entitlementService");
    	Resource res  =  entSer.getResource("concretepage.txt");
    	InputStream is =  res.getInputStream();
    	
    	try{
    		int i=0;
            while((i=is.read())!=-1)
            {
               char c=(char)i;
               System.out.print(c);
            }
        }catch(IOException e){
        	 e.printStackTrace();
         }finally{
            
           if(is!=null)
            is.close();
         }
    } 
}
 


spring-app.xml
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
     
	 <bean id="entitlementService" class="com.concretepage.EntitlementService"/>
	 
</beans>
 


Output
Hello World!
 
Download Source Code
resourceloaderaware-spring-example.zip
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us