Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring beans configuration

Tags:

java

spring

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 is in a JAR file on my classpath. I try to access it as follows:

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

however I keep getting encountering the following 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?

like image 360
cdugga Avatar asked Nov 17 '08 17:11

cdugga


2 Answers

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());
like image 165
toolkit Avatar answered Oct 12 '22 05:10

toolkit


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.

like image 33
Paul Gregoire Avatar answered Oct 12 '22 05:10

Paul Gregoire