1
我想在StaticApplicationContext中自动装入一个bean,但虽然我可以插入一个bean并成功检索它,但我无法在另一个bean中自动装入它。下面是一个简单的例子来解释我的意思。StaticApplicationContext中的autowire bean
在此示例中,第一个断言成功,第二个断言失败。请注意,如果我注释掉此方法的行,而取消注释使用AnnotationConfigApplicationContext的方法#2的行,自动装配将起作用。不过,我想使用StaticApplicationContext方法进行这项工作。
@Test
public void testAutowire() {
//context configuration approach #1
StaticApplicationContext context = new StaticApplicationContext();
context.registerSingleton("child", Child.class);
//context configuration approach #2
//AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Child.class);
Parent parent = new Parent();
context.getAutowireCapableBeanFactory().autowireBean(parent);
//this is successful
Assert.notNull(context.getBean(Child.class), "no bean found");
//this works only with AnnotationConfigApplicationContext and not with StaticApplicationContext
Assert.notNull(parent.child, "no child autowired");
}
public static class Parent {
@Autowired
Child child;
public Parent() {
}
}
public static class Child {
public Child() {
}
}
问题出在哪里?
尝试与上下文太注册父。 –
我试过了,它不能用于注册父项。事实上,我认为这样做并不合理,因为我在上下文之外手动创建父对象。这就是我需要使用autowireBean方法执行自动装配的原因 – Marios