tags:

views:

1829

answers:

4

I'm using Spring's dependency injection but I'm running into difficulty loading a resource in my spring config file.

The resource is an XML file and its in a jar file on my classpath. I try to access it as follows;

<import resource="classpath:com/config/resources.xml" />

however I keep geting error;

Failed to import bean definitions from URL location [classpath:com/config/resources.xml]

The jar file is on the classpath of a Java project which is in turn used by my web app. Should I really be doing my spring configuration in the web project as opposed the java project or does that matter?

+6  A: 

If it needs to be in the classpath of your webapp, then you should stick the JAR containing the config file into your WEB-INF/lib directory.

If you're using a webapp, then the common convention is use a ContextLoaderListener to ensure a WebApplicationContext is inserted into a standard place in the ServletContext:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/com/config/resources.xml</param-value>
</context-param>

Then use WebApplicationContextUtils to fish the application context out of the servlet context using:

WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
toolkit
A: 

I don't really recall why this matters, but try putting an asterisk () in front of the colon (:) classpath:/ If this doesn't work, try the asterisk after the colon (classpath:*), although I think it was before the colon.

MetroidFan2002
I think you are referring to this: http://static.springframework.org/spring/docs/2.5.x/reference/resources.html#resources-classpath-wildcards
matt b
A: 

I've only used the <import> directive in J2SE and it works without the classpath: prefix, simply as <import resource="config/resources.xml" />. But in J2EE if all your files are inside WEB-INF, it should be similar, just import resource="bla.xml" and it should find it, although in J2EE you don't need to do this because in web.xml you can define several files in the contextConfigLocation context parameter inside web.xml, just separate them with spaces or newlines.

Chochos
A: 

I ran into a similar issue with a red5 plugin. I resolved it like so:

try {
  subContext = new FileSystemXmlApplicationContext(new String[] { "classpath*:/myconfig.xml" }, true, context);
} catch (Exception fnfe) {
  subContext = new FileSystemXmlApplicationContext(new String[] { "plugins/myconfig.xml" }, true, context);
}

This will look anywhere on the classpath first, including within the jar that contains my code. If an exception occurs the plugin directory is checked. It may not be the best solution but it works.

Mondain