Spring 测试:如何启用 bean 的自动扫描

问题描述:

比如现在每节课我都要做

For example, now in each test class I have to do

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)

我想摆脱

 @ContextConfiguration(loader=AnnotationConfigContextLoader.class)

并希望 Spring 扫描我项目中的所有 bean.

and want Spring to scan all the beans in my project.

我该怎么做?

如果你在 xml 文件中有你的 spring 配置,你会使用类似的东西:

If you have your spring configuration in an xml file you would use something like:

@ContextConfiguration(locations="classpath:applicationContext.xml")

如果您使用 Java Config 那么您将使用

If you use Java Config then you would use

@ContextConfiguration(classes=Config.class)

我在上面的示例中使用了通用名称,您当然需要适应您的项目配置.

I used generic names in the above samples, you'll of course need to adapt to your project's configuration.

在这两种情况下,都需要启用 Spring 的组件扫描,以便 Spring 选取带注释的类.

In both cases Spring's component scanning will need to be enabled for Spring to pickup the annotated classes.