Announcement Announcement Module
Collapse
No announcement yet.
Getting a resource using application context? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Getting a resource using application context?

    Hi,
    I have some jobs that run, using Spring's JobDetailBean. I need one of the jobs to read and write files, so I want to load them in using getResourceAsStream, but I am not sure how to provide the context to my JobClass.

    Say, in my applicationContext.xml file, I have this:
    Code:
    <bean..... 
    <property name="jobDataAsMap">
    	    	<map>
    <entry key="logFileLocation"><value>classpath&#58;resources/logarchive.txt</value></entry>
    ....
    Can I, in my code, somehow get that file, via the application context?
    Code:
    context = new StaticWebApplicationContext&#40;&#41;;
    		Resource r = context.getResource&#40;logFileLocation&#41;;

  • #2
    ClassPathResource res = new ClassPathResource("beans.xml");
    XmlBeanFactory factory = new XmlBeanFactory(res);
    JobDetailBean jb = (JobDetailBean)factory.getBean("jobDetailBean");
    Map jobdata = jb.getJobDataAsMap();
    ...

    Comment


    • #3
      I need one of the jobs to read and write files, so I want to load them in using getResourceAsStream
      Are you open to a solution other than using getResourceAsSteam()?

      Maybe Spring's Resource interface will serve your purposes. It is a clean/elegant solution. Here is how I found out about it.

      http://forum.springframework.org/showthread.php?t=9703=

      I am using my own version of a configuration object, that receives several Resource objects so that it can receive an InputStream from files existing under application's WEB-INF directory. In turn, the configuration object is passed to another bean that actually uses the data from the files.

      In Spring, you get a resource like so:
      Code:
      <bean id="config1" class="pkg.xxx.MyConfigObject" 
         init-method="initialize">
        <property name="resource0">
          <value>WEB-INF/data/myDataFile.dat</value>
        </property>
      </bean>
      Where the config bean has a setResource0(Resource resource) method defined.

      Best Regards, feester

      PS
      And how do you do testing of your code outside a Servlet environment? While unfortunately you are coupling with Spring's core API by using Resource interface, you are decoupling your code from the Servlet API which simplifies testing.

      In my testing enviroment the data directory is included in the classpath and the bean definition changes slightly.

      Code:
      <bean id="config1" class="pkg.xxx.MyConfigObject" 
          init-method="initialize">
        <property name="resource0">
          <value>data/myDataFile.dat</value>
        </property>
      </bean>
      Last edited by robyn; May 14th, 2006, 11:44 AM.

      Comment

      Working...
      X