我在Stackoverflow和其他网站上就此问题阅读了很多帖子,但没有找到解决方案。
我有一个Maven模块的以下结构,其中一个主要父pom声明了所有这些模块(我在这里简化了结构以便只显示相关部分):
Maven modules http://i59.tinypic.com/fc0f91.png
基地和" A"模块依赖于base-api模块。基本模块包含base-api模块中包含的接口的实现。
我在" base-api"中有一个接口IFoo。模块。接口IFoo由" base"中的类Foo实现。模块。 Foo课程注释了Spring" @ Service"注解。
我希望Foo服务在我的测试类中自动装配,该测试类包含在模块中" A":
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class FooTest {
@Autowired
private IFoo foo;
我还为我的测试创建了一个上下文配置文件,其中包含以下行
<context:component-scan base-package="x.y.z"/>
IFoo和Foo都包含在x.y.z的子包中(在不同的maven模块中,如上所述)。
当我在Eclipse中运行测试(使用m2eclipse插件)时,它会正确传递。但是,当我运行maven构建(mvn clean install)时,会发生以下错误:
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [x.y.z.v.IFoo] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我做错了什么?
答案 0 :(得分:3)
如果module A
不依赖于base module
,则module A
上的任何执行都无法找到base module
中的任何组件。因此,module A
中依赖于base module
的实现的任何组件都将失败(因为从module A
看不到实现)。
如果您只是希望base module
可以访问module A
中的组件来运行测试,则可以使用base module
从module A
添加到scope
的依赖项设为test
。这样,您对module A
的测试就可以正常运行了。如果需要,您可以灵活地在运行时引入完全不同的JAR,并使用IFoo
的不同实现。