junit进行测试的时候无法注入接口?

package org.dao;

import org.entity.Seckill;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

import static org.junit.Assert.*;

/**
 * Created by Administrator on 16.11.11.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring/spring-dao.xml"})
public class SeckillDAOTest {



    @Resource
    private SeckillDAO seckillDAO;


    @Test
    public void queryById() throws Exception {
        Seckill seckill = seckillDAO.queryById(1000L);
        System.out.println(seckill.getName());
    }

    @Test
    public void reduceNumber() throws Exception {

    }

    @Test
    public void queryAll() throws Exception {

    }



}

上面是测试类, 在 private SeckillDAO seckillDAO处警告could not autowire. No beans of 'SeckillDAO' type found。然而spring-dao.xml已经配置了扫描接口


    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="org.dao"/>
    </bean>

该如何解决?

阅读 8.4k
2 个回答

确定加载到配置文件了吗?如果配置文件是放在resources下的话试试:

@ContextConfiguration(locations = {"classpath:spring/spring-dao.xml"})

或者其它你自己的配置文件的路径。

请问LZ最后处理了吗?我也遇到了这个问题,Tomcat是可以跑起来的,但junit跑起来的时候却提示No qualifying bean,我看了下target下的文件,xml文件是在的,网上找的很多方案都是说locations没有配置,但location是确定配置好了mybatis.xml和spring.xml、spring-mvc.xml的,现在还处理不了

我错误的原因找到了,原来是因为在mybatis.xml中,MapperScannerConfigurer等bean在<beans profile="t1"></beans>中配置了,Tomcat启动的时候,因为web.xml配置了
<param-name>spring.profiles.active</param-name>
<param-value>t1</param-value>
所以才可以正常运行,但在junit测试的时候没有写,导致扫描不到mapper,出现No qualifying bean,因为MapperScannerConfigurer这个类都没有注入,解决方法是在测试类加上@ActiveProfiles(value = "t1")

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题