Results 1 to 3 of 3

Thread: Getting Servlet Context path in Application Context

  1. #1
    Join Date
    Nov 2010
    Location
    Colorado
    Posts
    4

    Default 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. #2
    Join Date
    Oct 2005
    Location
    Mobile, AL
    Posts
    345

    Default

    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>

  3. #3
    Join Date
    Nov 2010
    Location
    Colorado
    Posts
    4

    Default 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.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •