spring依赖注入配置及简写形式

来源:互联网 发布:华为查看端口 编辑:程序博客网 时间:2024/06/07 19:55

总结一下依赖注入配置及简写形式,其实我们已经在以上部分穿插着进行简化配置了:

 

一、构造器注入:

1)常量值

简写:<constructor-arg index="0" value="常量"/>

全写:<constructor-arg index="0"><value>常量</value></constructor-arg>

2)引用

简写:<constructor-arg index="0" ref="引用"/>

全写:<constructor-arg index="0"><ref bean="引用"/></constructor-arg>

 

二、setter注入:      

       1)常量值

        简写:<property name="message" value="常量"/>

        全写:<property name="message"><value>常量</value></ property>

       2)引用

        简写:<property name="message" ref="引用"/>

        全写:<property name="message"><ref bean="引用"/></ property>

       3)数组:<array>没有简写形式

       4)列表:<list>没有简写形式

       5)集合:<set>没有简写形式

       6)字典

          简写:<map>

             <entry key="键常量" value="值常量"/>

             <entry key-ref="键引用" value-ref="值引用"/>

            </map>

         全写:<map>

             <entry><key><value>键常量</value></key><value>值常量</value></entry>

             <entry><key><ref bean="键引用"/></key><ref bean="值引用"/></entry>

           </map>

       7)Properties:没有简写形式

 

三、使用p命名空间简化setter注入:

       使用p命名空间来简化setter注入,具体使用如下:

 

 

java代码:
查看复制到剪贴板打印
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  xmlns="http://www.springframework.org/schema/beans"  
  3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.         xmlns:p="http://www.springframework.org/schema/p"  
  5.         xsi:schemaLocation="  
  6.            http://www.springframework.org/schema/beans  
  7.            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  8. <bean id="bean1" class="java.lang.String">  
  9.         <constructor-arg index="0" value="test"/>  
  10.     </bean>  
  11. <bean id="idrefBean1" class="cn.javass.spring.chapter3.bean.IdRefTestBean"  
  12. p:id="value"/>  
  13. <bean id="idrefBean2" class="cn.javass.spring.chapter3.bean.IdRefTestBean"  
  14. p:id-ref="bean1"/>  
  15. </beans>  
  • xmlns:p="http://www.springframework.org/schema/p" :首先指定p命名空间;
  • <bean id="……" class="……" p:id="value"/> :常量setter注入方式,其等价于<property name="id" value="value"/>;
    •  
      • <bean id="……" class="……" p:id-ref="bean1"/> :引用setter注入方式,其等价于<property name="id" ref="bean1"/>。 
原创粉丝点击