Spring 學習筆記 - IOC/依賴注入
阿新 • • 發佈:2018-10-31
簡述:
Spring 學習 - IOC/依賴注入
1. Bean 的例項化
1) 直接使用原始類建立bean
<bean id="exampleBean" class="com.anialy.test.ExampleBean" />
2) 使用工廠方法建立bean
</pre><pre name="code" class="html"><bean id="exampleBean" class="com.anialy.test.ExampleBean" factory-method="createInstance" />
<bean id="baseBean" class="com.anialy.test.BaseBean" />
<bean id="exampleBean" factory-bean="baseBean" factory-method="createInstance" />
2.Bean 注入方式
1)Setter Injection
<bean id="exampleBean" class="com.anialy.test.ExampleBean"> <property name="beanOne"> <ref bean="anotherExampleBean" /> </property> <property name="beanTwo" ref="yetAnotherBean" /> <property name="integerProperty" value="10" /> </bean>
2) Constructor Injection(建構函式注入)
<bean id="exampleBean" class="com.anialy.test.ExampleBean>
<constructor-arg type="int" value="100" />
<constructor-arg type="java.lang.String" value="stringVal" />
</bean>
3. 幾種特殊物件的注入
1)Inner Beans
<bean id="outter" class="com.anialy.test.Outter"> <property name="inner"> <bean class="com.anialy.test.Inner" /> </property> </bean>
2) Collections - Map
<bean id="exampleBean" class="com.anialy.test.ExampleBean">
<property name="map" >
<map>
<entry key="one" value="1.11" />
</map>
</property>
</bean>
3) NULLS
<bean class="com.anialy.test.ExampleBean">
<property name="name"><null /></property>
</bean>
4. Bean的scope
1. prototype, 每次getBean時都會建立一個新的例項
<bean id="exampleBean" class="com.anialy.test.ExampleBean" scope="prototype" />
2. singleton, 每次getBean時都獲取同一個例項
<bean id="exampleBean" class="com.anialy.test.ExampleBean" scope="singleton" />
5. 自定義初始化
1) 自定義
public class ExampleBean {
public void init() {
// do initialization work
}
}
<bean id="exampleBean" class="com.anialy.test.ExampleBean" init-method="init" />
2) 實現Spring約定的介面
public class ExampleBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
// TODO initialization work
}
}
6. 自定義銷燬
1)自定義
public class ExampleBean {
public void destroy() {
}
}
<bean id="exampleBean" class="com.anialy.test.ExampleBean" destroy-method="destroy" />
2)實現Spring提供的介面
public class ExampleBean implements DisposableBean {
@Override
public void destroy() throws Exception {
// do some destroy work
}
}
7. Bean的依賴
一個Bean必須等到其他bean被成功載入後才能載入
<bean id="bean2" class="com.anialy.test.Bean2" depends-on="bean1" />
<bean id="bean1" class="com.anialy.test.Bean1" />
8. Bean的延遲初始化
一個Bean只有當被其他Bean引用到,才真正建立例項
1) 單個Bean配置
<bean id="exampleBean" class="com.anialy.test.ExampleBean" lazy-init="true" />
2) 所有的Bean預設的延遲初始化配置
<beans default-lazy-init="true"></beans>
9. Bean的繼承
<bean id="parentBean" abstract="true" >
<property name="name">
<value>anialy</value>
</property>
<property name="age">
<value>11</value>
</property>
</bean>
<bean id="childBean" class="com.anialy.test.ChildBean" parent="parentBean">
<property name="name">
<value>anialy-child</value>
</property>
</bean>