PDA

View Full Version : Getting a resource URL in ApplicationContext?



mschuerig
Sep 6th, 2004, 04:57 AM
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



<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

Alef Arendsen
Sep 6th, 2004, 08:27 AM
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):



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

mschuerig
Sep 6th, 2004, 02:27 PM
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