简述:
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>