尝试IllegalStateException
JUnit 测试 MyBatis-Spring 项目时会遇到问题。
问题似乎出在自动装配MyBatis Mapper Beans 上(请原谅我的行话,因为我是整个 MyBatis-Spring-JUnit 设置的新手)。我从其他人那里继承了设置。让我知道是否有任何其他信息与获得帮助有关。
当我将整个事物公开为 Web 服务时,下面描述的设置有效。但是,当我尝试 JUnit 测试它时它失败了。如何在测试时自动装配映射器?
设置
在 main/java 下
- 持久性文件夹:ProductMapper.java
- 服务文件夹:ProductService.java
- ws 文件夹:BrowserService.java
- ws/impl 文件夹:BrowserServiceImpl.java
在主要/资源下
- 持久性文件夹:ProductMapper.xml
浏览器服务.java
class BrowserServiceImpl {
private ProductService productService;
// setters and getters
// Methods
}
产品服务.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.
...
编辑
请参阅上面更新的数据源BeanContext.xml
。配置看起来正确吗?
看起来一个问题是数据源设置。我做出这个假设是因为 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
当我将它放在正确的目录中时,它可以毫无问题地找到该文件。