Java @Autowired无法使用应用程序上下文文件中定义的bean

Java @Autowired无法使用应用程序上下文文件中定义的bean,java,spring,autowired,Java,Spring,Autowired,我在spring上下文文件“applicationContext.xml”中定义了一个bean,如下所示: <bean id="daoBean" class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="com.xxx.DAOImpl" /> </bean> 正在从JUnit测试类访问我的服务类 @RunWith(SpringJUnit4ClassR

我在spring上下文文件“applicationContext.xml”中定义了一个bean,如下所示:

<bean id="daoBean" class="org.mockito.Mockito" factory-method="mock">
        <constructor-arg value="com.xxx.DAOImpl" />
</bean> 
正在从JUnit测试类访问我的服务类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext.xml" }) 
public class JUnitTest{
    // other code here

    @Autowired
    private transient ServiceImpl serviceImpl;

    // test cases are here
}
当我执行测试用例时,它会给出错误提示:

创建名为“ServiceImpl”的bean时出错:自动连线依赖项的注入失败;嵌套异常为org.springframework.beans.factory.BeanCreationException:无法自动连接字段:private transient com.xxx.daimpl

当我从服务类中删除@Autowired并使用@Resource(name=“daoBean”)时,测试用例运行良好

public class ServiceImpl{
            // other code here

            @Resource(name = "daoBean")
            private transient DAOImpl daoBean;

            // other code here
        }
我的问题是为什么@Autowired在这种情况下不起作用?我是否需要使用@Autowired配置任何其他东西,以便它可以正常工作。我不想更改我的服务层类以替换@Autowired to@Resource。

有一个通用返回类型
t
,它在运行时被删除,因此Spring无法推断创建的模拟的类型,该模拟将在Spring上下文中简单地注册为
对象。这就是为什么
@Autowired
不起作用的原因(因为它试图按其类型查找依赖项)


查看问题的解决方案。

感谢您给出答案。现在我明白了。
public class ServiceImpl{
            // other code here

            @Resource(name = "daoBean")
            private transient DAOImpl daoBean;

            // other code here
        }