1.spring支持的属性注入的方法:构造函数注入,setter方法注入
User类,属性name,age
public class User { private String name; private Integer age; public User(String name, Integer age) { this.name = name; this.age = age; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public User() { }
@Override public String toString() { return "User{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘; } }
2.构造函数注入--<constructor-arg>(name,value,index,type,ref)
当属性中有了对象呢?
将<constructor-arg>或<property>中的value替换成ref即可,ref的值是对象属性在xml中的beanId
<bean id="user" class="com.pheony.demo4.User" > <constructor-arg name="name" value="张三"></constructor-arg> <constructor-arg name="age" value="35"></constructor-arg> </bean>
3.setter方法注入--<property>(name,value,ref)
<bean id="user1" class="com.pheony.demo4.User" > <property name="name" value="李四"></property> <property name="age" value="18"></property> </bean>
注:使用setter不仅要对属性添加set方法,当有有参构造方法的时候,需要添加上无参构造方法,否则没有<constructor-arg>会报错
p命名空间-------简化xml配置(spring2.5之后引入)
<bean id="user2" class="com.pheony.demo4.User" p:name="王五" p:age="23" p:cat-ref="cat" />
SpEL注入:spring表达式语言,对依赖进行简化
语法:value="#{表达式}"
4.复杂类型属性的注入
数组类型 private String[] arrs;
<property name="arrs"> <list> <value>aaa</value> <value>bbb</value> <value>ccc</value> </list> </property>
List集合类型 private List<String> list;
<property name="list"> <list> <value>111</value> <value>222</value> <value>333</value> </list> </property>
Set集合类型 private Set<String> set;
<property name="set"> <set> <value>ddd</value> <value>eee</value> <value>fff</value> </set> </property>
Map集合类型 private Map<String,Integer> map;
<property name="map"> <map> <entry key="a" value="1"></entry> <entry key="b" value="2"></entry> <entry key="c" value="3"></entry> </map> </property>
Properties类型 private Properties properties;
<property name="properties"> <props> <prop key="username" >root</prop> <prop key="password" >root</prop> </props> </property>
原文地址:https://www.cnblogs.com/sycamore0802/p/11732127.html
时间: 2024-11-05 13:50:12