我有這個類彈簧試驗如果類解決它的自動裝配依賴
@Component("A")
public class A {
private B b;
@Autowired
public A(B b) {
this.b = b;
}
}
和其他類
@Component("B")
public class B {
public B() {
}
}
現在我已經寫了這個測試
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class ConstructorAutowiredTest {
@Configuration
static class ContextConfiguration {
@Bean
public B getBBean() {
B b = new B();
return b;
}
}
@Autowired
private B b;
@Test
public void isDependencyResolved() {
assertNotNull(b);
}
}
它的工作原理好。但有什麼方法可以測試這個B
bean是否自動注入到A
中。我想這樣的東西,但顯然它不工作。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class ConstructorAutowiredTest {
@Configuration
static class ContextConfiguration {
@Bean
public B getBBean() {
B b = new B();
return b;
}
}
@Autowired
private A a;
@Autowired
private B b;
@Test
public void isDependencyResolved() {
assertNotNull(b);
assertNotNull(a);
}
}
例外:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.abc.ConstructorAutowiredTest':
Unsatisfied dependency expressed through field 'a'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'com.abc.A' available: expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
好。很明顯,測試失敗了,因爲依賴性沒有被解決,至少你現在知道了。你的問題到底是什麼? –
我沒有看到你想在這裏測試的東西。您只是測試您的測試部署配置。重點是什麼? –
@Pablo我知道。但是我無法弄清楚如何在這裏指定'@ComponentScan(「com.abc」)'這樣的東西。 – sof