【发布时间】:2012-10-19 07:36:32
【问题描述】:
IllegalStateException 在尝试 JUnit 测试 MyBatis-Spring 项目时被抛出。
问题似乎出在 Autowiring MyBatis Mapper Beans 上(请原谅我的行话,因为我是整个 MyBatis-Spring-JUnit 设置的新手)。我从其他人那里继承了设置。让我知道是否有任何其他信息与获取帮助相关。
当我将整个事物公开为 Web 服务时,下面描述的设置有效。但是,当我尝试 JUnit 测试它时它失败了。如何在测试时自动装配映射器?
设置
main/java下
- 持久性文件夹:ProductMapper.java
- 服务文件夹:ProductService.java
- ws 文件夹:BrowserService.java
- ws/impl 文件夹:BrowserServiceImpl.java
在主/资源下
- 持久性文件夹:ProductMapper.xml
BrowserService.java
class BrowserServiceImpl {
private ProductService productService;
// setters and getters
// Methods
}
ProductService.java
class ProductService {
@Autowired
private ProductMapper productMapper;
// Methods
}
上下文.xml
<beans>
<bean id="browserSvc" class="com.comp.team.proj.ws.impl.BrowserServiceImpl">
<property name="productService" ref="productService" />
</bean>
<!-- MyBatis Config -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.comp.team.proj.persistence" />
<property name="annotationClass" value="org.springframework.stereotype.Repository"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@xxx.xxx.xxx.com:xxxx:xxx"/>
<property name="username" value="myusername"/>
<property name="password" value="mypassword"/>
</bean>
<!-- Other beans -->
</beans>
如果你好奇异常是什么样子的:
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private com.comp.team.proj.persistence.ProductMapper
com.comp.team.proj.service.ProductService.productMapper;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [com.comp.team.proj.persistence.ProductMapper]
found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this
dependency.
...
编辑
查看上面更新的Context.xml 中的数据源Bean。配置看起来正确吗?
dataSource 设置似乎存在一个问题。我做出这个假设是因为 JUnit 测试运行,但抛出了异常。所以,最有可能的不是 JUnit 设置。如果dataSource设置正确,MyBatis会成功实例化Mapper Bean,Autowiring也会成功。
测试文件
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class ProductCountTest {
@Autowired
protected BrowserService browserSvc;
@Test
public void testGetProductCount() {
long count = browserSvc.getProductCount();
assertTrue(count > 0);
}
}
它找到Context.xml 文件没有任何问题,因为我将它放在正确的目录中。
【问题讨论】:
-
你的测试代码在哪里......你还需要从测试类配置自动装配......并且你需要使用诸如runwithjunit4class和contextconfiguration(“locationof dispatcherservlet.xml”)之类的注释。
-
如果你正在测试一个使用自动装配的类,你应该使用 pawelccb 建议的代码。如果你不给出 pawelccb 给出的那些注释,通常是错误的。事情是如果我们不给出 dispatcherservlet.xml 的路径,那么测试类不知道自动装配问题,其中组件扫描是识别自动装配类的关键..