Announcement Announcement Module
Collapse
No announcement yet.
Getting Servlet Context path in Application Context Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Getting Servlet Context path in Application Context

    I have a Spring MVC app that uses an embedded database. I'd like the database file to be located relative to the web app context so I don't have to hard code a file path that may not be valid on different servers.

    The service that starts the database and provides access is declared as a bean in my applicationContext.xml:
    <bean id="graphDatabaseService" class="org.neo4j.kernel.EmbeddedGraphDatabase" destroy-method="shutdown">
    <constructor-arg index="0" value="path/to/db"/>
    </bean>

    The path provided to the bean constructor needs to be a file system path to the database directory.

    How do I specify a Servlet relative path in a Context xml file?
    If I were doing this programatically outside of Spring I'd probably use
    request.getSession().getServletContext().getRealPa th("path/to/db");

    I'm very new to Spring, so I apologize if this is simple and I missed it in the docs.

    Thanks.

  • #2
    I believe that all you need to do is define the constructor argument of type "Resource" and spring will automatically convert the string into it's Resource abstraction and then you can grab the file reference within the Resource.

    For example:

    Code:
    package com.foo;
    
    public class TestBean {
        private Resource resource;
        
        public TestBean(Resource aResource) {
            resource = aResource;
            //resource.getInputStream();
            //resource.exists();
            
        }
    }
    Code:
    <bean name="testBean" class="com.foo.TestBean">
        <constructor-arg value="/db/mydb.file" />
    </bean>

    Comment


    • #3
      Thanks

      Thanks Marty. But in this case the bean being initialized is not my class but a third party class, so I can't redefine the constructor arg. I could wrap the initialization in a delegate but that seems like overkill just to get a resource reference in an application context.

      This doesn't seem like such an unusual use case.

      Comment

      Working...
      X