简体   繁体   中英

spring beans configuration

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?

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());

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.

我真的不记得为什么这很重要,但是尝试在冒号(:)类路径前放一个星号( :/如果这不起作用,请尝试使用冒号后的星号(classpath:*),尽管我认为它在结肠之前。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM