Sunday, October 17, 2010

Injecting file dependency into Spring bean

Continuing to explore power of Spring Framework, I would like to explain how to inject file resource into the Spring bean using @Resource annotation.

First of all, let's start with beans definition file. We need basically to declare file dependency we would like to inject:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
  xsi:schemaLocation="
 
   <context:annotation-config />  
   <context:component-scan base-package="org.example" />
 
   <bean id="source" class="org.springframework.core.io.ClassPathResource">
      <constructor-arg index="0" value="some.file.txt" />
   </bean>
 
</beans>

Having configuration part is ready, we can inject file to a bean.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package org.example;
 
import java.util.List;
 
import javax.annotation.Resource;
 
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamSource;
import org.springframework.stereotype.Component;
 
@Component
public class SomeBean implements InitializingBean {  
 @Autowired @Resource( name = "source" ) private InputStreamSource source;
  
 public SomeBean () {
 }
  
 @Override
 public void afterPropertiesSet() throws Exception {
     for( final String line: ( List< String > )IOUtils.readLines( source.getInputStream() ) ) {
                // do something here   
     }
 }
}
That's it :)
Pretty easy and powerful technique.