为什么以下内容不适用于自动装配
问题描述:
我有类像为什么以下内容不适用于自动装配
class A {
@Autowired
B b;
}
A a = new A()
我发现b
不是自动装配的
我已经做过<context:component-scan base-package="*">
,还有其他什么遗失?
答
您必须从bean工厂获取bean,而不是直接创建实例。
例如,以下是如何使用注释执行此操作。首先,你需要更多的添加到您的类的声明:
// Annotate to declare this as a bean, not just a POJO
@Component
class A {
@Autowired
B b;
}
接下来,你这样做每个应用程序一次:
AnnotationConfigApplicationContext factory =
new AnnotationConfigApplicationContext();
factory.register(A.class);
factory.register(B.class);
// Plus any other classes to register, or use scan(packages...) method
factory.refresh();
最后,您现在可以得到的情况下,豆:如果Spring实例化它作为一个bean
// Instead of: new A()
A a = factory.getBean(A.class);
+0
我注意到你也在使用XML配置。没关系;只需获取应用程序上下文(也是bean工厂)并使用它的'getBean'方法。 – 2011-05-04 08:03:34
答
Spring将自动装配仅在A
对象。如果你实例化自己,Spring对此一无所知,所以没有任何东西会自动装配。
有没有关于B类定义的任何注释? – naiquevin 2011-05-04 07:50:30