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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23416366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:41:38  来源:igfitidea点击:

Spring Testing: How to enable auto-scan of beans

springunit-testingspring-test

提问by user3594176

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

例如,现在在每个测试类中我必须做

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

I want to get rid of

我想摆脱

 @ContextConfiguration(loader=AnnotationConfigContextLoader.class)

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

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

How can I do that?

我怎样才能做到这一点?

采纳答案by geoand

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

如果您在 xml 文件中有您的 spring 配置,您将使用以下内容:

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

If you use Java Config then you would use

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

@ContextConfiguration(classes=Config.class)

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

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

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

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

回答by Biju Kunjummen

You can do this:

你可以这样做:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {

  @Test
  public void testSomething() {

  }

  @Configuration
  @ComponentScan("basepackage")
  public static class SpringConfig {

  }
}

By default @ContextConfigurationwill look for static inner classes annotated with @Configuration, which is why this set up will just work.

默认情况下,@ContextConfiguration将查找用 注释的静态内部类@Configuration,这就是为什么这个设置会起作用的原因。

You can get rid of loader param altogether, that is not required

您可以完全摆脱 loader 参数,这不是必需的

回答by Barett

You can also simply add @SpringBootTestif using Spring Boot.

@SpringBootTest如果使用 Spring Boot,您也可以简单地添加。