java如何从另一个maven模块导入Spring应用程序上下文?
我的项目中有两个模块,它们是主应用程序的子模块。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文件就是这样。它们的所有依赖项webapp和commons都继承自app。pom。 commons和webapp都使用Spring 3。描述应用程序上下文的xml文件。 在webapp模块中,我想使用commons模块中的bean。以下是公共空间的应用程序上下文:
<?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>
对于webappapplicationContext。我有:
<?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 楼答案
如果它不在子目录下,例如
spring/applicationContext-commons.xml
,那么以下(您已经尝试过)应该可以工作:带星号的Spring将使用类路径上的所有匹配文件,没有星号的Spring将使用它找到的第一个文件
此外,如果找不到文件,带星号的Spring将忽略该文件。如果没有星号,Spring将在找不到文件时出错。因此,您的文件不在类路径上
我会检查
applicationContext-commons.xml
在target
文件夹下的位置,以确保<import resource=
有正确的路径,并从根pom重新运行mvn install