学习目标:
学习如何对spring对象进行赋值以及复杂的类型如何赋值学习内容:
1. 简单的单类赋值 2、类加类(引用类) 3、 复杂的类型如何赋值(集合,数组)学习内容:
1.给简单的类赋值
简单的类注入赋值方式:
1.set赋值
这种是最简单的赋值
<bean name="user" class="cn.oracle.pojo.User">
<property name="name" value="老王"></property>
<property name="password" value="隔壁"></property>
</bean>
2.构造赋值
<bean name="user2" class="cn.oracle.pojo.User">
<!-- 构造注入 index是为了在构造多的时候确认是哪一个-->
<constructor-arg name="name" value="张三" index="0" type="java.lang.String"></constructor-arg>
<constructor-arg name="password" value="1234556" index="1" type="java.lang.String"></constructor-arg>
</bean>
3.P空间赋值
P空间赋值要在约束那里加上一段,
xmlns:p="http://www.springframework.org/schema/p"
<!-- p空间赋值需要上面加入xmls:p的链接属性,并采用p:属性名来赋值 -->
<bean name="user3" class="cn.oracle.pojo.User" p:name="小强" p:password="效力" p:address-ref="Address"></bean>
4spel注入属性.
<!-- spel注入:spring表达语言 -->
<bean name="user4" class="cn.oracle.pojo.User">
<!-- 引入别的bean的属性固定格式#{ -->
<property name="name" value="#{user2.name}"></property>
<property name="password" value="#{user.password}"></property>
</bean>
类加类
就是类中引入别的类。
比如我用户类引入了address类
那么我就这样配置
<bean name="Address" class="cn.oracle.pojo.Address">
<property name="city" value="长安"></property>
<property name="street" value="北大街"></property>
</bean>
引用赋值
<property name="address" ref="Address"></property>
然后测试
@Test
public void test() {
//创建容器
ApplicationContext ac=new ClassPathXmlApplicationContext(“applicationContext.xml”);
User us=(User)ac.getBean(“user”);
System.out.println(us);
}
输出
结果
二:复杂的类型注入
先上测试的主角们
然后我们挨个测试
<!-- 复杂类型注入,map测试 -->
<bean name="Collection3" class="cn.oracle.pojo.Collection">
<property name="map">
<map>
<entry key="老大" value="王家老大"></entry>
<entry key="老二" value="王家老二"></entry>
<entry key="老二" value-ref="user2"></entry>
</map>
</property>
</bean>
<!-- 负责类型注入,prop(hashtable子类) -->
<bean name="Collection4" class="cn.oracle.pojo.Collection">
<property name="prop">
<props>
<prop key="一">士兵</prop>
<prop key="二">列兵</prop>
</props>
</property>
</bean>
测试一下:
输出结果i
public void testpro() {
//创建容器,加载xml文件
ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("cn/oracle/pojo/applicationContext.xml");
//ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Collection c2=(Collection)ac.getBean("Collection4");
//获取集合
Properties prop=c2.getProp();
//获取键
Set<Object> keySet=prop.keySet();
for (Object key : keySet) {
Object value=prop.get(key);
System.out.println(key+",键"+value);
}
System.out.println("===============");
Properties pr = c2.getProp();
Set<Entry<Object, Object>> entrySet2 = prop.entrySet();
for (Map.Entry entry2 : entrySet2) {
System.out.println(entry2.getKey() + " , " + entry2.getValue());
}
好了,基本都跑通了,任务完成