DI
DI全称:Dependency Injection又称作依赖注入,依赖注入的好处是可扩展。
依赖注入的分类:
1.设值注入
在设值注入中,Bean必须有针对该属性的setter方法,并且Bean定义文件中有该属性的设值,例如:
Java类
1 public class HelloWorld { 2 3 private String name; 4 5 6 public void setName(String name) { 7 8 this.name = name; 9 } 10 }
配置文件
1 <bean id = "helloworld" class = "com.feimao.DI.test.HelloWorld"> 2 3 <property name = "name" ref = "feimao"/>
构造方法注入
可以使用<construct-arg>元素来表示构造方法注入
关于构造参数顺序
通过定义文件的书写顺序,例如:
1 public class User { 2 3 private Integer age; 4 private String name; 5 public User(Integer age , String name) { 6 7 this.age = age; 8 this.name = name; 9 } 10 }
定义文件
1 <bean id = "user" class = "com.feimao.DI.test.User"> 2 < construct-arg value = "28"/> 3 < construct-arg value = "feimao"/> 4 </bean>
如果有两个相同的属性,通过index属性指定
定义文件
1 <bean id = "user" class = "com.feimao.DI.test.User"> 2 < construct-arg value = "28" index = “0”/> 3 < construct-arg value = "feimao" index = “1”/> 4 </bean>
值属性
可以直接使用<value> </value>元素或者value属性来设置基本类型和字符串
推荐使用:
1 <bean id = "user" class = "com.feimao.DI.test.User"> 2 < property name = “name” value = "feimao"/> 3 < property name = “age” value = "28"/> 4 </bean>
依赖注入的属性设置
空值null
1 <bean id = "user" class = "com.feimao.DI.test.User"> 2 < property name = “name”> 3 <null/> 4 /property> 5 </bean>
如果是空字符串,写成这样<value></value>即可
集合对象属性
通过<list/>、<set/> <map/>及<props/>可以定义和设置与Java Collection集合类型对应的List、Set、Map及Properties的值
List
1 < property name = “someList”> 2 <list> 3 <value>a list element followed by a reference</value> 4 <ref bean=”myDataSource”/> 5 </list> 6 </property>
Set
1 < property name = “someSet”> 2 <set> 3 <value>just some string</value> 4 <ref bean=”myDataSource”/> 5 </set> 6 </property>
Map
1 < property name = “someMap”> 2 <map> 3 <entry> 4 <key> 5 <value>yup a entry</value> 6 </key> 7 <value> just some string </value> 8 </entry> 9 </map> 10 </property>
Properties
1 < property name = “adminEmails”> 2 <props> 3 <prop key=”administrator@somecompany.org”</prop> 4 <prop key=”support@somecompany.org”</prop> 5 <prop key=”development@somecompany.org”</prop> 6 </props> 7 </property>