
這節內容講的是 Spring 容器在初始化階段,如果是 stand-alone 應用,使用傳統的 Java main() 方法創建容器的話。那么剛開始那個階段算是 dependency-pull 類型的控制反轉。就兩個文件,一個主啟動類,一個xml配置文件如下:
```java
public class DependencyPull {
public static void main(String... args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext
("spring/app-context.xml");
MessageRenderer mr = ctx.getBean("renderer", MessageRenderer.class);
mr.render();
}
}
```
~~~xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="provider" class="com.apress.prospring5.ch2.decoupled.HelloWorldMessageProvider"/>
<bean id="renderer" class="com.apress.prospring5.ch2.decoupled.StandardOutMessageRenderer"
p:messageProvider-ref="provider"/>
</beans>
~~~
不過上邊的 xml 配置文件當中 bean 的類型是引用了第二章 hello-world 工程中的代碼,這樣復用,而不是復制的方式,會好一些。