Spring支持3种依赖注入的方式 (DI依赖注入)
*属性注入 (配置bean set方法注入)
<bean id="car" class="spring.beans.di.Car">
<property name="brand" value="AuDi"></property>
<property name="crop" value="ShangHai"></property>
<property name="price" value="400000"></property>
<property name="maxSpeed" value="240"></property>
</bean>
*构造器注入 (配置bean 通过构造器的方法给对象的属性注入值)
<bean id="car1" class="spring.beans.di.Car">
<constructor-arg value="bmw" index="" type="java.lang.String"></constructor-arg>
<constructor-arg value="DG" index=""></constructor-arg>
<constructor-arg value="50000" index="" type="double"></constructor-arg>
</bean>
*Bean与Bean引用关系 ( 配置Bean 通过 ref )
<bean id="person" class="spring.beans.di.Person">
<property name="name" value="贾1"></property>
<property name="age" value="20"></property>
<property name="car" ref="car1"></property>
</bean>
*内部的Bean的使用
<bean id="person1" class="spring.beans.di.Person"> <property name="name" value="贾2"></property> <property name="age" value="30"></property> <property name="car"> <bean class="spring.beans.di.Car"> <property name="brand" value="DasAuto"></property> <property name="crop" value="ShanHan"></property> <property name="price" value="300000"></property> <property name="maxSpeed" value="300"></property> </bean> </property> </bean>
<!-- null值与级联属性的赋值-->
<bean id="person2" class="spring.beans.di.Person"> <property name="name" value="贾3"></property> <property name="age" value="40"></property> <!-- <property name="car"><null /></property> --> <property name="car" ref="car1"></property> <!-- 级联属性赋值的时候,当前级联的对象必须是存在的. --> <property name="car.maxSpeed" value="250"></property> </bean>
*List集合属性的注入
<bean id="personList" class="spring.beans.di.collections.PersonList"> <property name="name" value="xxxx"></property> <property name="age" value="25"></property> <property name="cars"> <list> <ref bean="car1"/> <ref bean="car2"/> <bean class="spring.beans.di.Car"> <property name="brand" value="AuDi"></property> <property name="crop" value="ShangHai"></property> <property name="price" value="400000"></property> <property name="maxSpeed" value="240"></property> </bean> </list> </property> </bean>
*Map集合属性注入值
<bean id="personMap" class="spring.beans.di.collections.PersonMap">
<property name="name" value="jjjjj"></property>
<property name="age" value="29"></property>
<property name="cars">
<map>
<entry key="AA" value-ref="car1"></entry>
<entry key="BB" value-ref="car2"></entry>
</map>
</property>
</bean>
*给Properties类型的属性注入值 (数据源)
<bean id="dataSource" class="spring.beans.di.collections.DataSource"> <property name="properties"> <props> <prop key="user">root</prop> <prop key="password">1234</prop> <prop key="url">jbdc:mysql://localhost:3306/test</prop> <prop key="driverClass">com.mysql.jbdc.Driver</prop> </props> </property> </bean>
备注:
1. <![CDATA[ 什么内容都可以写,并且只是返回的是字符串的格式 ]]>