springmvc-spring使用JUnit时autowired报错,controller里面autowired可以的

问题描述

spring使用JUnit时autowired报错,controller里面autowired可以的

试了好多办法还是不行,不知道哪里配错了。。麻烦大神帮看一下
异常信息:

 SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5f98de7] to prepare test instance [com.xxx.xxx.entity.UserTest@42d33bc1]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.xxx.xxx.entity.UserTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.xxx.xxx.service.UserService com.xxx.xxx.entity.UserTest.service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.xxx.xxx.service.UserService] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.xxx.xxx.service.UserService com.xxx.xxx.entity.UserTest.service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.xxx.xxx.service.UserService] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
    ... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.xxx.xxx.service.UserService] 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)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
    ... 28 more

UserTest.java

 package com.xxx.xxx.entity;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.xxx.xxx.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:**/applicationContext.xml","classpath*:**/springmvc-servlet.xml"})
public class UserTest {

    @Autowired
    UserService service;

    //@Ignore
    @Test
    public void userHPTest() {
        System.out.println(service.get("889e4d63ff024b29a173ab52ce174cc9"));
    }

}

UserServiceImpl.java(这个是service的实现)

 package com.xxx.xxx.serviceimpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xxx.xxx.dao.BaseDao;
import com.xxx.xxx.dao.UserDao;
import com.xxx.xxx.entity.User;
import com.xxx.xxx.service.UserService;

@Service("userServiceImpl")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    UserDao dao;

    @Override
    protected BaseDao<User> getDao() {
        return dao;
    }

}

applicationContext.xml(我感觉我可能是这里不对)

 <?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:jdbc="http://www.springframework.org/schema/jdbc"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:util="http://www.springframework.org/schema/util"
     xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
        <context:component-scan base-package="com.xxx.xxx.dao"></context:component-scan>
        <context:component-scan base-package="com.xxx.xxx.daoimpl"></context:component-scan>
        <context:component-scan base-package="com.xxx.xxx.service"></context:component-scan>
        <context:component-scan base-package="com.xxx.xxx.serviceimpl"></context:component-scan>
</beans>

springmvc-servlet.xml(我在controller里autowired是没有问题的)

 <?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 

    <context:component-scan base-package="com.xxx.xxx.controller"></context:component-scan>
    <context:component-scan base-package="com.xxx.xxx.dao"></context:component-scan>
    <context:component-scan base-package="com.xxx.xxx.daoimpl"></context:component-scan>
    <context:component-scan base-package="com.xxx.xxx.service"></context:component-scan>
    <context:component-scan base-package="com.xxx.xxx.serviceimpl"></context:component-scan>
    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

解决方案

不好意思,我没看你的问题就先回答了。重新郑重回答一次:我按照你写的测试用例,测了下自己项目中的Service类,是可以的。报这个错还是说明你的UserService的实现类没有被扫描到,你检查下扫描路径看看,确定UserServiceImpl 和BaseUserServiceImpl 都在扫描路径下。
你让我也受教了,原来可以直接用SpringJunit测试,本人知识浅薄,以前竟然都是用那么原始的方法测试的。祝好!

解决方案二:

junit测试这个方法的时候你要自己去获取userService这个服务,junit单元测试其实是一个独立的单元测试,它跟Spring的容器是没有关系的。示例代码如下:我的spring的配置文件在WebContent/WEB-INF/config下。

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.bohui.css.service.CurUserService;

import junit.framework.Assert;
import junit.framework.TestCase;

/**
 * @title TestUserService
 * @author WoodWang
 * @description setUp中编写代码获取Bean实例
 * @date   2015-4-11
 * @version 1.1.0
 */
public class TestUserService extends TestCase {

    private CurUserService userService;

    @Override
    protected void setUp() throws Exception {
        ApplicationContext ac = new FileSystemXmlApplicationContext("WebContent/WEB-INF/config/applicationContext.xml");
        userService = (CurUserService)ac.getBean("cuserService");
        System.out.println(userService==null);
    }

    public void testGetValue(){
        Assert.assertEquals(userService.getValue(), 10);
    }
}

解决方案三:

谁帮我看看啊。。。真是不知道嗯么办

时间: 2025-01-24 08:52:10

springmvc-spring使用JUnit时autowired报错,controller里面autowired可以的的相关文章

ssh整合-spring整合hibernate做测试时没有报错,当三个整合时启动就报错啦,求大神指点!!

问题描述 spring整合hibernate做测试时没有报错,当三个整合时启动就报错啦,求大神指点!! 报的错误org.springframework.scheduling.quartz.JobMethodInvocationFailedException: Invocation of method 'ecsUnsigned' on target class [class $Proxy17] failed; nested exception is org.springframework.tran

spring和mybatis集成时总报错 麻烦帮忙看下什么原因

问题描述 spring和mybatis集成时总报错 麻烦帮忙看下什么原因 项目请求数据的时候报Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.business.dao.system.AdminMapper.selectByPrimaryKey麻烦大神帮忙看下这是啥原因,找了好久不知道

spring mvc-求解 springMVC可以使用 加入第三方jar包报错

问题描述 求解 springMVC可以使用 加入第三方jar包报错 提示如下 : java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: Root WebApplicationContext: startup date [Thu Mar 03 09:57:48 CST 2016];

求助!tomcat启动正常,访问javaweb时控制台报错

问题描述 求助!tomcat启动正常,访问javaweb时控制台报错 访问javaweb项目时报错,在myeclise6.0上无该异常,在myeclise10上报如下异常:org.apache.catalina.core.StandardWrapperValve invoke严重: Servlet.service() for servlet jsp threw exceptionjavax.xml.parsers.FactoryConfigurationError: Provider org.a

使用commons-fileupload时启动报错

问题描述 使用commons-fileupload时启动报错 使用commons-fileupload时启动报java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory错误,最开始都是可以使用的,后来改了下配置文件的配置就开始报错,生成的target目录下是有那个配置文件的 在maven已经导入了commons-fileupload包: <dependency> <groupId>com

加载mvc项目时,报错,才接触mvc,不知道如何解决

问题描述 加载mvc项目时,报错,才接触mvc,不知道如何解决 加载mvc项目时,报错,才接触mvc,不知道如何解决,报错说是,没有什么model,url等字段 解决方案 什么mvc,spring mvc还是asp.net mvc,什么报错,贴出完整信息. 解决方案二: 是asp.net mvc, 解决方案三: 先ctrl+f5编译下,然后重新打开项目看看.

求助:summernote+spring mvc图片上传报错

问题描述 求助:summernote+spring mvc图片上传报错 先是controller代码: @ResponseBody @RequestMapping("/sumimg.do") public Result upload(HttpServletRequest request) { Result result = new Result(); // 转换为文件类型的request MultipartHttpServletRequest multipartRequest = (M

spring mvc与struts 整合报错

问题描述 spring mvc与struts 整合报错 报错如下求帮忙,谢谢严重: Exception starting filter struts2Unable to load configuration. - action - file:/E:/java/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/bishe/WEB-INF/classes/struts.xml:11:74 at org.apa

【Spring实战】—— 12 AspectJ报错:error at ::0 can&#039;t find referenced pointcut XXX

今天在使用AspectJ进行注解切面时,遇到了一个错误. 切点表达式就是无法识别--详细报错信息如下: Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xingoo' defined in class path resource [bean.xml]: Initialization of bean fail