Spring框架学习(二)

一、依赖注入的三种注入方式

  Spring框架为我们提供了三种注入方式:set注入、构造方法注入和接口注入。

  1、set注入

    规律:无论给什么赋值,配置文件中<property>标签的name属性值一定和对象中的名称一致。

    1)普通字符类型注入

1 <bean id="" class="">
2     <property name="" value=""/>
3 </bean>
View Code

    

    2)对象注入

1 <bean id="" class="">
2     <property name="" ref=""/>
3 </bean>
View Code

    3)list集合注入

1 <bean id="" class="">
2     <property name="">
3         <list>
4             <value></value>
5             <value></value>
6             <value></value>
7         </list>
8     </property>   
9 </bean>                                
View Code

    4)属性文件中的字段的注入

1 <bean id="" class="">
2     <property name="props">
3          <props key=""></props>
4          <props key=""></props>
5          <props key=""></props>
6     </property>
7 </bean>
8 
9 注意:props是类中的资源文件类的对象
View Code

     

  2、构造方法注入

    1)一个参数

    

1 <bean id="" class="">
2       <constructor-args value=""/>
3 </bean>
View Code

    2)两个参数

      当参数为非字符串类型时,在配置文件中需要制定类型,如果不指定类型一律按照字符串类型赋值。

      当参数类型不一致时,框架是按照字符串的类型进行查找的,因此需要在配置文件中制定是参数的位置。

     

1 <constructor-arg value="admin" index="0"/>
2 <constructor-arg value="23" type="int" index="1"/>
View Code
原文地址:https://www.cnblogs.com/lynujyq/p/5265849.html