大家好,在 Spring boot 文档中,它说
如果请求类型有多个 bean,则必须在字段级别指定限定符元数据:
@SpyBean @Qualifier("example") private ExampleService service;
这在 Spring boot 1.5.19.RELEASE 上对我不起作用。简单的例子是
@SpringBootApplication
public class QualifierspyApplication {
public static void main(String[] args) {
SpringApplication.run(QualifierspyApplication.class, args);
}
@Primary
@Bean("simpleService1")
public SimpleService simpleService1() {
return new SimpleService("hello 1");
}
@Bean("simpleService2")
public SimpleService simpleService2() {
return new SimpleService("hello 2");
}
}
测试是
@RunWith(SpringRunner.class)
@SpringBootTest
public class QualifierspyApplicationFailingTest {
@SpyBean
@Qualifier("simpleService2")
private SimpleService simpleService2;
@Test
public void testSpy() {
Assert.assertEquals("hello 2", simpleService2.method());
}
}
该测试仅在我输入@SpyBean(name = "simpleService2")
.如果我删除@Primary
它会失败
java.lang.IllegalStateException: No bean found for definition [SpyDefinition@209da20d name = '', typeToSpy = se.lolotron.qualifierspy.SimpleService, reset = AFTER]
您可以在此处找到示例。