ResourceLoaderAware : When we load resources using bean, ResourceLoaderAware will help us to load resources using getter/setter methods.
For more details see my last blog Click
Below example will help you to understand better:
Create CustomerService.java and implement ResourceLoaderAware interface.
package com.bhagwan.customer.services;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
public class CustomerService implements ResourceLoaderAware
{
private ResourceLoader resourceLoader;
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public Resource getResource(String location){
return resourceLoader.getResource(location);
}
}
Spring-Customer.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="customerService"
class="com.bhagwan.customer.services.CustomerService" />
</beans>
BeanResourceApp.java
package com.bhagwan.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.bhagwan.customer.services.CustomerService;
public class BeanResourceApp
{
public static void main( String[] args )
{
ApplicationContext appContext =
new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
CustomerService cust =
(CustomerService)appContext.getBean("customerService");
Resource resource =
cust.getResource("classpath:com/bhagwan/common/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();
}
}
}
0 Comment(s)