如何从另一个 Maven 模块导入 Spring 应用程序上下文?

How to import Spring application context from another maven module?

我的项目中有两个模块是主 app.pom

的子模块
<modules>
    <module>commons</module>
    <module>webapp</module>
</modules>

webapp模块这样引用commons

    <dependency>
        <groupId>com.app.whatever</groupId>
        <artifactId>commons</artifactId>
        <version>${project.version}</version>
    </dependency>

commons 模块只是打包在 .jar 文件中,仅此而已。它们的所有依赖项 webappcommons 都继承自 app.pomcommonswebapp 都使用 Spring 3 和描述应用程序上下文的 .xml 文件。 在 webapp 模块中,我想使用来自 commons 模块的 bean。这是 commons:

的 applicationContext
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="com.app.whatever.anything"/>
</beans>

对于 webapp applicationContext.xml 我有:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<import resource="classpath*:/applicationContext-commons.xml"/>

<context:component-scan base-package="com.app.whatever.something.controller.spring"/>

但不幸的是,这不起作用。尽管在设置上述 maven 依赖项后,我可以在第一个模块中使用第二个模块中的任何 类,但总是出现关于没有自动装配候选人的异常。 当我写这个没有星号的导入时,它说文件不存在。 我试过没有前导斜杠 - 同样的例外。

此导入非常适用于同一模块中的任何文件,甚至适用于我拥有的外部库。但它无法从我刚刚创建的这个新 commons 模块解析文件。

如果您有任何想法,那将非常有帮助,谢谢

如果它不在子目录下,例如spring/applicationContext-commons.xml 那么以下(您已经尝试过的)应该有效:

<import resource="classpath*:applicationContext-commons.xml"/>

如果有星号,Spring 将使用类路径中的所有匹配文件,没有星号它将使用找到的第一个文件。

此外,带星号 Spring 的文件如果未找到,将忽略该文件。没有星号 Spring 如果找不到文件会报错。因此您的文件不在类路径中。

我会检查 applicationContext-commons.xmltarget 文件夹下的位置,确保 <import resource= 的路径正确,然后重新 运行 mvn install从根 pom.