您的位置:首页 > 运维架构

property和constructor-arg设值注入

2016-06-09 16:23 281 查看
一、注入的方式 

配置文件的根元素是beans,每个组件使用bean元素来定义,如果使用设值注入,可以利用以下方式,来指定组件的属性。

  constructor-arg:通过构造函数注入。 

  property:通过setxx方法注入。 

二、使用方法

(1)property的简单使用

spring的xml配置文件:

<bean id="baseInfo" class="com.learn.spring.baseInfo">
<property name="name" value="sky"/>
<property name="age" value="24"/>
</bean>
java文件:

package com.learn.spring;
public class baseInfo {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}(2)constructor-arg的简单使用
spring的xml配置文件:

<bean id="man" class="com.learn.spring.Man">
<!-- 当构造函数有多个参数时,可以使用index属性,index属性的值从0开始 -->
<constructor-arg value="zzy" index="0">
</constructor-arg>

<!-- 在使用构造子注入时,需要注意的问题是要避免构造子冲突的情况发生
如 man(String value) man(int value)构造函数冲突
使用type属性制定参数类型,明确的告诉需要使用哪个构造函数 -->
<constructor-arg value="10" type="int" index="1">
</constructor-arg>

<constructor-arg>
<list>
<value>movie</value>
<value>music</value>
</list>
</constructor-arg>

<constructor-arg>
<set>
<value>Lady is GaGa</value>
<value>GaGa is Lady</value>
</set>
</constructor-arg>

<constructor-arg>
<map>
<entry key="zhangsan" value="male"></entry>
<entry key="lisi" value="female"></entry>
</map>
</constructor-arg>

<!-- 最后一个参数是boolean类型的参数,在配置的时候可以是true/false或者0/1 -->
<constructor-arg index="5" value="0">
</constructor-arg>

<constructor-arg>
<props>
<prop key="name">sky</prop>
</props>
</constructor-arg>
</bean>
为了注入集合属性,Spring提供了list,map,set和props标签,分别对应List,Map,Set和Properties,我们甚至可以嵌套的使用它们(List of Maps of Sets of Lists)。

java文件:

public class Man {
private String name;
private int age;
private List hobby;
private Map friends;
private Set set;
private boolean ifMarried;    
private Properties properties;
public Man() {
}
public Man(String name, int age, List hobby, Map friends, Set set, boolean ifMarried, Properties properties) {
this.name = name;
this.age = age;
this.hobby = hobby;
this.friends = friends;
this.set = set;
this.ifMarried = ifMarried;
     this.properties = properties;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息