Spring inject resources

Spring inject resources :To load static resource file by spring injection please have below code.

1. Create bean class name SpringResourceInjection.java

package com.javahonk.di.bean;

import org.springframework.core.io.Resource;

public class SpringResourceInjection {

    private Resource textFile;

    public void setTextFile(Resource textFile) {
	this.textFile = textFile;

    public Resource getTextFile() {
	return textFile;


2. Create ResourceTestFile.txt which we are going to read and enter below line for test to read:

Resource test = Successfull


3. Create context file name: springResourceContext.xml with include bean definition shown below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

<bean id="resourceInjection" class="com.javahonk.di.bean.SpringResourceInjection">
	<property name="textFile" value="spring/ResourceTestFile.txt"></property>



4. Create java main class to load context file and get bean to read resource file:

package com.javahonk;

import java.io.InputStream;
import java.util.Scanner;

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

import com.javahonk.di.bean.SpringResourceInjection;

public class ReadSpringResourceFile {
    public static void main(String[] args) throws Exception {
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
	InputStream inputStream = null;
	Scanner scanner = null;
	try {

	    SpringResourceInjection springResourceInjection = applicationContext

	    Resource springBeanInjectedResource = springResourceInjection
	    inputStream = springBeanInjectedResource.getInputStream();
	    scanner = new Scanner(inputStream);
	    while (scanner.hasNext()) {

	} finally {
	    if (inputStream != null) {
	    if (null != scanner) {



5. Final project snap shot:

Spring inject resources

6. Finally we are ready to run main class which will read spring\ResourceTestFile.txt and print output on console. To Run –> Right click ReadSpringResourceFile.java –> Run As –> Java Appliction then you will below output on console:

Spring inject resources

7. That’s it.

Spring inject resources Download project : Spring inject resources


Leave a Reply

Your email address will not be published. Required fields are marked *