[英]SpringJUnit4ClassRunner with declarative and annotated beans
I have a declarative spring config 我有一个声明性的spring配置
@Configuration
public class SpringConfig {
@Bean
public someBean() {
return new Bean1();
}
}
and a @Component annotated Bean 和一个@Component注释的Bean
@Component
public class Bean2 {
}
Now I would like to use both of then in my UnitTest 现在我想在我的UnitTest中同时使用
@RunWith(SpringJUnit4ClassRunner.class)
public void UnitTest {
@Autowired Bean1 bean1;
@Autowired Bean2 bean2;
}
but I have no idea how to do it. 但我不知道该怎么做。
You can do this: 你可以这样做:
@ContextConfiguration(classes = {SpringConfig.class})
@RunWith(SpringJUnit4ClassRunner.class)
public void UnitTest {
@Autowired Bean1 bean1;
@Autowired Bean2 bean2;
}
For class Bean2, you can add the @ComponentScan annotation: 对于Bean2类,可以添加@ComponentScan批注:
@Configuration
@ComponentScan("com....package.of.bean2")
public class SpringConfig {
@Bean
public someBean() {
return new Bean1();
}
}
If you don't want to add the ComponentScan to your SpringConfig class, you can add an additional test config class with the ComponentScan annotation and add it to the ContextConfiguration annotation: 如果您不想将ComponentScan添加到SpringConfig类,则可以使用ComponentScan批注添加其他测试配置类,并将其添加到ContextConfiguration批注:
@ContextConfiguration(classes = {SpringConfig.class, SpringTestConfig.class})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.