Home Tutorial Spring Spring3 Ioc Spring ResourceLoaderAware

 
 

Spring ResourceLoaderAware
Posted on: September 6, 2010 at 12:00 AM
Advertisement
In this tutorial you will learn about spring ResourceLoaderAware.

Spring ResourceLoaderAware

We use the ResourceLoader when your application object need to access different type of file resources. In this tutorial you will see an example of how to use ResourceLoaderAware interface.

StudentBean.java

package com.roseindia.student.services;

import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

public class StudentService implements ResourceLoaderAware {
	private ResourceLoader resourceLoader;

	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	public Resource getResource(String location) {
		return resourceLoader.getResource(location);
	}
}

AppMain.java

package com.roseindia.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;

import com.roseindia.student.services.StudentService;

public class AppMain {

	public static void main(String[] args) throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"context.xml");
		StudentService bean = (StudentService) ctx.getBean("studentBean");

		Resource resource = ctx.getResource("file:c:\\testing.txt");
		try {
			InputStream is = resource.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));

			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			br.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="studentBean" class="com.roseindia.student.services.StudentService" />
</beans>

When you run this application it will display message as shown below:


This is test file.

Download this example code

Advertisement

Related Tags for Spring ResourceLoaderAware:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 6, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com