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

  • Getting a resource URL in ApplicationContext?

    I have a bean, MyDigester, that internally uses a Digester to create objects from an XML file. The digester rules are not defined programmatically, but rather in a file /WEB-INF/mydigester.xml.

    MyDigester's ctor takes as a single argument a URL to the digester rules. Thus, in the bean definition, I'd like to write something like this

    Code:
      <bean
       id="mydigester"
       class="...MyDigester"
       singleton="false">
       <constructor-arg><value>/WEB-INF/mydigester.xml</value></constructor-arg>
      </bean>
    Presumably the value string is automatically converted to a URL, but unfortunately, java.net.URL seems to accept only absolute URLs.

    Programmatically I can get at the URL with
    appctx.getResource("/WEB-INF/mydigester.xml").getURL(), but I don't see a way to do it declaratively, which I'd prefer obviously.

    Michael

  • #2
    You'd have to register a customereditorconfigurer along with a PropertyEditor that is capable of resolving Strings to URLs. The difficulty here is that you need the servletcontext or the application context.

    This is resolved by extending implementing ApplicationContextAware and casting it to a WebApplicationContext (so this only works in WebApplicationContext):

    Code:
    public void UrlResourceEditor 
    extends PropertyEditorSupport 
    implements ApplicationContextAware &#123;
    
      ApplicationContext ctx;
      public void setApplicationContext&#40;&#41; &#123; .. &#125;
    
      public void setAsText&#40;String text&#41; &#123;
        WebApplicationContext webAppCtx = &#40;WebApplication&#41;ctx;
        Resource res = webAppCtx.getResource&#40;text&#41;;
        setValue&#40;res.getUrl&#40;&#41;&#41;;
      &#125;
    &#125;
    Register the custom editor using the CustomEditorConfigurer (see sect. 3.13 of the reference manual).

    Comment


    • #3
      There already is org.springframework.beans.propertyeditors.URLEdito r which currently just passes the string to the ctor of java.net.URL. If the URL string is relative, the latter will throw a MalformedURLException. In this case, wouldn't it be better, if the URLEditor would resolve relative URLs? I'm an utter newbie regarding Spring, thus I'm not sure whether a PropertyEditor can usefully be ApplicationContextAware.

      Michael

      Comment

      Working...
      X