How to override the behavior of Spring @Autowired

A little background:

I am Using Spring 2.5, and specifically Spring IOC and annotations.

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.

Now to the problem:

Note: I use a different Spring Context for the Test environment.

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 ).

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).

I am looking for a way to inject the test bean instead of the original 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

All these options seem to exists only for the beans which were originally defined in the Spring Context Configuration file.


使用ReflectionTestUtils手动设置模拟代替自动装配的依赖关系(为此目的,你的模拟不能被弹簧管理,以便不存在任何歧义)


I know this question is quite old but a I think an answer might still be useful for others.

Since you probably do not want to mix both Foo and MockFoo within your context, I would suggest to remove Foo from the component-scanning. This could be done for example by specifying include/exclude filters on the <context:component-scan> .

However if you are implementing unit tests, I would rather suggest not using a Spring context and just implementing "pure" unit tests by injecting mock-ups of the dependencies manually, so that you are only testing a single class. This can be achieved more easily by using a mocking framework like Mockito.


I agree with Didier. Here is an example of how you can exclude the implementations that you want to mock in your test application context.

<context:component-scan base-package="com.company" >
    <context:exclude-filter type="regex" expression="com.abc.service.XDaoImpl"/>    
</context:component-scan>

Include this application context in your test as follows :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/applicationContext-test.xml"})
public class MyTest {....}
链接地址: http://www.djcxy.com/p/67720.html

上一篇: 如何使用IntelliJ IDEA查找所有未使用的代码?

下一篇: 如何覆盖Spring @Autowired的行为