我正在尝试在 StaticApplicationContext 中 Autowiring 一个 bean,但是尽管我可以插入一个 bean 并成功检索它,但我无法在另一个 bean 中 Autowiring 它。下面是一个简单的例子来解释我的意思。
在此示例中,第一个断言成功,第二个断言失败。请注意,如果我注释掉此方法的行,并取消注释使用 AnnotationConfigApplicationContext 的方法 #2 的行,则 Autowiring 将起作用。不过,我想使用 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() {
}
}
有什么想法问题出在哪里吗?
最佳答案
AnnotationConfigApplicationContext
在内部注册一个 AutowiredAnnotationBeanPostProcessor
bean 来处理 @Autowired
注解。 StaticApplicationContext
没有。
您可以自己添加
context.registerSingleton("someName", AutowiredAnnotationBeanPostProcessor.class);
但是您需要刷新
ApplicationContext
context.refresh();
关于java - StaticApplicationContext 中的 Autowiring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31208148/