Spring Resource Example

In this tutorial you will learn about spring resource example.

 
 

Share on Google+Share on Google+

Spring Resource Example

Ads

In this tutorial you will learn about spring resource example.

Spring Resource Example

The Resource interface is used as an argument type in many method signatures when a resource is need. In this example you will see how to use Resource interface in spring framework.

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;

public class AppMain {

	public static void main(String[] args) throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"context.xml");
	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">

</beans>

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


This is test file.

Download this example code

Advertisements

Posted on: September 6, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles