如何覆盖Spring @Autowired的行为 [英] How to override the behavior of Spring @Autowired
问题描述
有一点背景:
我正在使用Spring 2.5,特别是Spring IOC和注释。
I am Using Spring 2.5, and specifically Spring IOC and annotations.
我在我的代码中使用 @Autowired
(自动装配由类型完成)
并使用 @Component
I am using @Autowired
in my code (the Autowiring is done by type)
and use @Component
for exposing classes to the automatic wiring.
当我尝试测试我的代码时,下面描述的情况出现。
The situation described below arose while I tried to test my code.
现在问题:
注意:我为测试环境使用了不同的Spring上下文。
Note: I use a different Spring Context for the Test environment.
我有一个类 FOO
这是 @Autowired
,但在测试上下文中,我想使用不同类的相同类型 MockFoo
(extends FOO
)。
I have a class FOO
which is @Autowired
but in the test context I want to use a different class of the same type MockFoo
(extends FOO
).
Spring设置当然自动失败,因为 FOO
类的依赖注入的多个选项( FOO
和 MockFOO
符合类型检查)
The Spring setup of course fails automatically due to multiple options for the Dependency Injection of the FOO
class (both FOO
and MockFOO
comply to the Type check).
我正在寻找一种注入测试bean而不是原来的bean。
I am looking for a way to inject the test bean instead of the original bean.
我希望Spring允许使用Context配置文件来覆盖一个bean注入或者不要命令Spring不自动连接一个特定的bean。
I expected Spring to allow using the Context configuration file to override a bean injection or to order Spring not to autowire a specific bean.
BUT
所有这些选项似乎只适用于Spring Context配置文件中最初定义的bean。 >
All these options seem to exists only for the beans which were originally defined in the Spring Context Configuration file.
推荐答案
使用 ReflectionTestUtils
手动设置Mock代替自动连线依赖(为此,您的模仿不能被弹簧管理,所以不存在歧义)
Use ReflectionTestUtils
to manually set the Mock in place of the autowired dependency (for that purpose your mock must not be spring managed, so that no ambiguity exists)
这篇关于如何覆盖Spring @Autowired的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!