2020.11.05
1、构造方法(construct-arg)
1、默认调用无参构造方法
2、有参构造方法:
(1)基本数据类型:
public Student(int age) {
System.out.println("Students"+""+age);
}
<bean name="student" class="com.jd.vo.Student">
<constructor-arg index="0" value="12"/>
</bean>
直接在constructor-arg标签中的value参数赋值即可
(2)引用数据类型
public Student(Date birth){
System.out.println(birth+"//");
}
<bean name="date" class="java.util.Date"></bean>
<bean name="student" class="com.jd.vo.Student">
<constructor-arg ref="date"/>
</bean>
需要使用ref标签,在其中指定引用标签的name即可
(3)List标签
public Student(List<String> names)
{
for (String name:names)
System.out.println(name);
}
<bean name="wang" class="java.lang.String">
<constructor-arg value="王五"></constructor-arg>
</bean>
<bean name="num" class="java.lang.Integer">
<constructor-arg value="5"> </constructor-arg>
</bean>
<bean class="com.jd.vo.Student" lazy-init="true">
<constructor-arg>
<list>
<value>1</value>
<value>2</value>
<bean class="java.lang.Integer">
<constructor-arg value="3"/>
</bean>
<ref bean="num"></ref>
</list>
</constructor-arg>
</bean>
(4)Set类型
public Student(Set<String> mobiles)
{
for (String i:mobiles)
System.out.println(i);
}
<bean class="com.jd.vo.Student" lazy-init="true">
<constructor-arg>
<set>
<value>1</value>
<value>2</value>
<bean class="java.lang.Integer">
<constructor-arg value="3"/>
</bean>
<ref bean="num"></ref>
</set>
</constructor-arg>
</bean>
(5)Map
public Student(Map<String,String> teachers)
{
Set<String> set = teachers.keySet();
for(String key:set)
System.out.println(key+","+teachers.get(key));
}
注意获取Map数据的方法,还有一种entry方法也可以
<bean class="com.jd.vo.Student">
<constructor-arg>
<map>
<entry key="liming" value="119"></entry>
<!--<entry key-ref="k" value-ref="v"></entry>-->
</map>
</constructor-arg>
</bean>
</beans>
String不能使用ref引用,即不能做成一个Bean会报错,不知道为什么,String也有构造方法呀
(6)properties类型
public Student(Properties properties)
{
System.out.println(properties.getProperty("name"));
System.out.println(properties.getProperty("mobile"));
}
这种数据类型类似于数据库配置文件的key-val类型
<bean class="com.jd.vo.Student">
<constructor-arg>
<props>
<prop key="name">zhangsan</prop>
<prop key="mobile">110</prop>
</props>
</constructor-arg>
</bean>
2、Set方法(property)
1、普通类型
private String name;
public void setName(String name) {
this.name = name;
}
<bean class="com.jd.vo.Student">
<property name="name" value="张三"></property>
</bean>
使用set方法就不是constructor标签了,而是使用property的方法进行赋值
※使用命名空间p:
先使用p:name="Jim"然后Alt+Enter直接自动引入
<bean class="com.jd.vo.Student" p:name="Jin"></bean>
2、数组类型
public void setScores(int[] scores) {
this.scores = scores;
}
<bean class="com.jd.vo.Student">
<property name="scores" >
<array>
<value>78</value>
<value>90</value>
</array>
</property>
</bean>
p命名空间:
<bean class="com.jd.vo.Student" p:scores-ref="s"></bean>
<util:array id="s">
<value>98</value>
<value>99</value>
</util:array>
注意,引用util时候idea要在引入的xml的基础上引入xsi,即在xml的左边点小黄灯泡然后点add