Spring ResourceLoaderAware Example

By Arvind Rai, July 10, 2022
The ResourceLoaderAware interface to be implemented by any object that wishes to be notified of the ResourceLoader that it runs in. The ApplicationContext is the sub-interface of ResourceLoader interface. The ResourceLoaderAware is an alternative to a full ApplicationContext dependency via the ApplicationContextAware interface.
Find the 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! 

Reference

Interface ResourceLoaderAware

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us