我有Component
註釋的接口和一些類,實現它,如下所示:如何在沒有Spring XML上下文文件的情況下AutoWire對象?
@Component
public interface A {
}
public class B implements A {
}
public class C implements A {
}
另外,我有一個Autowired
變量像這樣的類:
public class Collector {
@Autowired
private Collection<A> objects;
public Collection<A> getObjects() {
return objects;
}
}
我的背景文件由這些定義:
<context:component-scan base-package="org.iust.ce.me"></context:component-scan>
<bean id="objectCollector" class="org.iust.ce.me.Collector" autowire="byType"/>
<bean id="b" class="org.iust.ce.me.B"></bean>
<bean id="c" class="org.iust.ce.me.C"></bean>
而在主類中,我有一些代碼如下:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
B b = (B) context.getBean("b");
C c = (C) context.getBean("c");
Collector objectCollector = (Collector) context.getBean("objectCollector");
for (A object : objectCollector.getObjects()) {
System.out.println(object);
}
輸出:
[email protected]
[email protected]
這些代碼工作得很好,但由於某些原因,我不願意用XML上下文文件。除此之外,我傾向於使用new
運算符創建對象,而不是使用getBean()
方法。儘管如此,由於AutoWiring
在編程中確實是個好主意,我不想失去它。
現在我有兩個問題!
我怎麼能
AutoWire
類,實現了A
界面不使用XML上下文文件?
有沒有可能?當我改變從
singlton
bean的scope
到prototype
如下:<bean id="b" class="org.iust.ce.me.B" scope="prototype"></bean>
和實例數它的豆子,只有在創造
context
中實例化的豆,是injected
成AutoWired
變量。爲什麼?
任何幫助將不勝感激。
優秀!希望我可以給予超過+1。感謝您查找併發布代碼 - 絕不會讓它在文檔中變得如此之低...... 與Neo4j一起工作非常精彩(通過[this](http://codepitbull.wordpress.com/2013/05/12/bootstrapping -neo4j與 - 彈簧 - 數據 - 不-XML))。 再次,謝謝! – KendallV