另外,J2EE中从Context取得对象也属于type 1。
它依赖于配置文件
- <container>
- <component name=“kissable“ class=“Boy">
- <configuration> … </configuration>
- </component>
- <component name=“girl" class=“Girl" />
- </container>
IOC type 2:
- public class Girl {
- private Kissable kissable;
- public void setKissable(Kissable kissable) {
- this.kissable = kissable;
- }
- public void kissYourKissable() {
- kissable.kiss();
- }
- }
Type 2出现于Spring Framework,是通过JavaBean的set方法来将需要的Boy传递给Girl。它必须依赖于配置文件。
- <beans>
- <bean id=“boy" class=“Boy"/>
- <bean id=“girl“ class=“Girl">
- <property name=“kissable">
- <ref bean=“boy"/>
- </property>
- </bean>
- </beans>
IOC type 3
- public class Girl {
- private Kissable kissable;
- public Girl(Kissable kissable) {
- this.kissable = kissable;
- }
- public void kissYourKissable() {
- kissable.kiss();
- }
- }
这就是PicoContainer的组件 。通过构造函数传递Boy给Girl。
- PicoContainer container = new DefaultPicoContainer();
- container.registerComponentImplementation(Boy.class);
- container.registerComponentImplementation(Girl.class);
- Girl girl = (Girl) container.getComponentInstance(Girl.class);
- girl.kissYourKissable();
原文链接:http://liangthinking.iteye.com/blog/507345