将模型注入具有 @Autowired 注释的 bean [英] inject a mockups to a bean that has @Autowired annotations

查看:23
本文介绍了将模型注入具有 @Autowired 注释的 bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 bean,其中有几个 bean 注入了自动装配注释(无限定符).现在,出于测试原因,我想向 bean 注入一些模拟,而不是自动装配的模拟(一些 DAO).有什么方法可以在不修改 bean 的情况下更改正在注入的 bean?我不喜欢在我的代码中添加注释只是为了测试它然后删除然后用于生产的想法.我使用的是 spring 2.5.

I have a bean that has a couple of beans injected with the autowire annotation (no qualifier). Now, for testing reasons I want to inject some mocks to the bean instead of the ones being autowired (some DAOs). Is there any way I can change which bean is being injected without modifying my bean? I don't like the idea of adding annotations my code just to test it and then remove then for production. I am using spring 2.5.

豆子看起来像这样:

@Transactional  
@Service("validaBusinesService")  
public class ValidaBusinesServiceImpl implements ValidaBusinesService {

    @Autowired  
    OperationDAO operationDAO;  
    @Autowired  
    BinDAO binDAO;  
    @Autowired  
    CardDAO cardDAO;  
    @Autowired  
    UserDAO userDAO;  

    ...
    ...
}

推荐答案

使用 ReflectionTestUtils 在单元测试中手动设置不同的实现.

Use ReflectionTestUtils to set a different implementation manually in your unit tests.

这实际上是依赖注入的强大功能之一——对于类如何注入它的依赖并不重要.

This is actually one of the powers of dependency injection - it doesn't matter to the class how its dependencies are injected.

这篇关于将模型注入具有 @Autowired 注释的 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆