IOC:控制反转,把对象交给框架创建
基于xml的IOC
- spring默认使用无参构造创建对象,但当有参构造覆盖了无参构造时,需注入有参构造的参数
//存在无参构造,创建对象
<bean id="acountDao" class="cn.itcast.dao.impl.AccountDaoImpl">
</bean>
//无参构造不存在,只有有参构造创建对象
<bean id="acountDao" class="cn.itcast.dao.impl.AccountDaoImpl">
<!-- 使用参数类型,注入 -->
<constructor-arg type="java.lang.String" value="hello"></constructor-arg>
<!-- 使用参数名,注入-->
<!-- <constructor-arg name="message" value="hello"></constructor-arg>-->
<!-- 使用参数位置,注入 -->
<!-- <constructor-arg index="0" value="hello"></constructor-arg>-->
</bean>
- 依赖注入:给对象的属性赋值
属性值是基本类型+String型时
<bean id="acount" class="cn.itcast.pojo.Account" scope="singleton">
<!--这是set方法注入属性值(对象),要求该属性有set方法 -->
<property name="name" value="lili"></property>
<property name="money" value="2300"></property>
</bean>
属性值是pojo型时
<bean id="user" class="cn.itcast.pojo.User" scope="prototype" init-method="init" destroy-method="destroy">
<property name="name" value="lili"></property>
<property name="age" value="12"></property>
</bean>
<bean id="account" class="cn.itcast.pojo.Account">
<property name="user" ref="user"></property>
</bean>
*属性值是集合类型时,使用 <array><list><set>标签 *
<bean id="user" class="cn.itcast.pojo.User" scope="prototype" init-method="init" destroy-method="destroy">
<property name="name" value="lili"></property>
<property name="age" value="12"></property>
<property name="password" value="132994334"></property>
<property name="accounts" >
<!-- <array>-->
<!-- <value>hello</value>-->
<!-- <value>india</value>-->
<!-- <value>mi</value>-->
<!-- <value>fans</value>-->
<!-- </array>-->
<set>
<value>hello</value>
<value>india</value>
<value>mi</value>
<value>fans</value>
</set>
<!-- <list>-->
<!-- <value>hello</value>-->
<!-- <value>india</value>-->
<!-- <value>mi</value>-->
<!-- <value>fans</value>-->
<!-- </list>-->
</property>
属性值是Map型时
<bean id="user" class="cn.itcast.pojo.User" scope="prototype" init-method="init" destroy-method="destroy">
<property name="accountMap">
<map>
<entry key="name" value="leijun"></entry>
<entry key="age" value="23"></entry>
<entry key="king" value="mr.wang"></entry>
</map>
</property>
</bean>
- scope init-method destroy-method属性
scope:singleton,prototype
singleton:单例模式 创建容器时创建对象,容器销毁时销毁对象
prototype:多例模式,用到时创建对象,长时间不用时,垃圾回收机制回收
init-method:创建对象时,执行对象的哪个方法,一般用于初始化对象属性值
destroy-method:销毁对象时,执行对象的哪个方法
<bean id="user" class="cn.itcast.pojo.User" scope="prototype" init-method="initNumber" destroy-method="destroyNumber">
</bean>