报错提示:
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
根据错误信息【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得初始化成功。
不要注入 用getBean
那说明你注入失败了。两种注入方式(1)原始的接口注入,需要getbean(2)mapper注入,不需要getbean.
推荐使用mapper...你的问题,用楼上的getbean试试。