首页 新闻 赞助 找找看

spring+mybatis用junit进行测试无法依赖注入

0
悬赏园豆:40 [已解决问题] 解决于 2016-10-19 10:49

报错提示:

 Error creating bean with name 'com.spring.test.UserServiceTest': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spring.service.IUserService com.spring.test.UserServiceTest.userService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.spring.service.IUserService] 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)}

 测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration   
(locations={"classpath*:config/spring/springmvc.xml","classpath*:config/spring/applicationContext-*.xml","classpath*:config/mybatis/sqlMapConfig.xml"})
public class BaseJunit4Test {
}
public class UserServiceTest extends BaseJunit4Test {
    private static Logger logger = Logger.getLogger(UserServiceTest.class);
    long startruntime = 0;
    long endruntime = 0;
    
    @Before
    public void before(){
        startruntime=System.currentTimeMillis(); //获取开始时间
    }
    @After
    public void after(){
        endruntime=System.currentTimeMillis(); //获取开始时间
        logger.info("此次方法运行时间: "+(endruntime-startruntime)+"ms");
    }
    
    @Autowired
    private IUserService userService;
    
    @Test
    public void loginTest() throws Exception {
        User user = userService.login("admin", "admin", null);
        logger.info(user.toString());
    }
}

去掉

@Autowired
private IUserService userService;
修改LoginTest()
@Test
public void loginTest() throws Exception {
    logger.info("test");
}

无注入能够正常运行测试,@Autowired注入就会报错Error creating bean

Ctony的主页 Ctony | 初学一级 | 园豆:15
提问于:2016-07-22 10:50
< >
分享
最佳答案
0

根据错误信息【No qualifying bean of type [com.spring.service.IUserService] found for dependency:】

spring找不到这样的一个类来装配,所以报这个错了。那么咱们要检查:

1.你的IUserService  具体的实现类在springbean的管理之下了吗,有没有加注解@Service 或者@Component  .?  

2.所在的包是否被扫描到了。  

3.如果都没问题,那么是不是 这个IUserService具有多个实现类,那么就需要使用@Qualifier("userService1")  @Qualifier("userService2")来指定是哪个实现。

楼上所说的用getBean 什么的。一样的,前提是 spring得初始化成功。

收获园豆:40
逃离沙漠 | 菜鸟二级 |园豆:259 | 2016-08-26 18:00
其他回答(2)
0

不要注入 用getBean

laugher_ccc | 园豆:593 (小虾三级) | 2016-07-22 10:54
0

那说明你注入失败了。两种注入方式(1)原始的接口注入,需要getbean(2)mapper注入,不需要getbean.

推荐使用mapper...你的问题,用楼上的getbean试试。

弦断有谁听 | 园豆:20 (初学一级) | 2016-07-22 11:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册