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

时间:2019-12-18 15:05:32

标签: java spring maven multi-module

我的项目中有两个模块,它们是主要 app.pom

的子级
<modules>
    <module>commons</module>
    <module>webapp</module>
</modules>

网络应用模块通过这种方式引用常见

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

常见模块只是打包在.jar文件中,仅此而已。它们的所有依赖项 webapp 常见均继承自 app.pom 常见 webapp 都使用Spring 3和.xml文件来描述应用程序上下文。 在 webapp 模块中,我要使用 commons 模块中的bean。这是常见的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 模块解析文件。

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

1 个答案:

答案 0 :(得分:1)

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

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

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

此外,带有星号的Spring会忽略该文件(如果未找到)。如果没有星号,Spring将无法找到该文件,并给出错误消息。因此,您的文件不在类路径中。

我将检查applicationContext-commons.xml文件夹下target的位置,以确保<import resource=具有正确的路径,然后从根pom重新运行mvn install。 / p>

相关问题