Spring的三种注入类型

来源:互联网 发布:人体辉光 知乎 编辑:程序博客网 时间:2024/05/16 23:39

   针对注入的值,Spring支持三种类型:字面值、其他Bean的引用和集合类型。


1.字面值

   字面值一般指的是可用字符串表示的值,在Spring配置文件中,如果Bean需要注入的值是字面值,则可通过<bean>或者<constructor-arg>的<value>子元素或value属性注入,如:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">           <bean id="book" class="com.loster.li.Book"><property name="name" value="SSH开发"></property><property name="author" value="xiaoli"></property><property name="publishHouse" ><value>某出版社</value></property><property name="price"><value>45</value></property></bean></beans>

2.其他Bean的引用

   如果Bean需要注入的属性是对象类型,则可以引用IoC容器中定义的类型匹配的其他Bean。引用其他Bean时可以通过<bean>或<constructor-arg>的<ref>子元素或者ref属性注入。

   假设在上面的Book类中添加一个属性Item(是Item类的一个对象),而且Item类的属性包含id和count,则xml应该为:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">           <bean id="book" class="com.loster.li.Book"><property name="name" value="SSH开发"></property><property name="author" value="xiaoli"></property><property name="publishHouse" ><value>某出版社</value></property><property name="price"><value>45</value></property><property name="Item" ref="Item1"></property><bean id="Item1" class="com.loster.li.Item"><property name="id" value="10"></property><property name="count" value="100"></property></bean></bean></beans>

3.集合类型

   Spring还支持对Bean的集合类型属性进行注入,<array>、<list>、<set>、<map>和<prop>元素分别用来设置类型为数组、List、Set、Map和Properties的集合属性值。

0 0
原创粉丝点击