我有这个类弹簧试验如果类解决它的自动装配依赖
@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