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" 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-3.0.xsd"> <bean id="resourceInjection" class="com.javahonk.di.bean.SpringResourceInjection"> <property name="textFile" value="spring/ResourceTestFile.txt"></property> </bean> </beans>
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( "spring/springResourceContext.xml"); InputStream inputStream = null; Scanner scanner = null; try { SpringResourceInjection springResourceInjection = applicationContext .getBean("resourceInjection", SpringResourceInjection.class); Resource springBeanInjectedResource = springResourceInjection .getTextFile(); inputStream = springBeanInjectedResource.getInputStream(); scanner = new Scanner(inputStream); while (scanner.hasNext()) { System.out.println(scanner.nextLine()); } } finally { if (inputStream != null) { inputStream.close(); } if (null != scanner) { scanner.close(); } } } }
5. Final project snap shot:
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:
7. That’s it.
Download project : Spring inject resources