gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:22:02 27 4
gpt4 key购买 nike

我的项目中有两个模块,它们是主 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 依赖项后我可以在第一个模块中使用第二个模块中的任何类,但不断出现关于没有 Autowiring 候选者的异常。当我编写这个不带星号的导入时,它表示该文件不存在。我尝试不带前导斜杠 - 同样的异常(exception)。

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

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

最佳答案

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

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

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

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

我会检查 applicationContext-commons.xml 的位置下target文件夹以确保 <import resource=路径正确并重新运行mvn install来自根 pom。

关于java - 如何从另一个maven模块导入Spring应用程序上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59394817/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com