依赖注入之set注入
1、常量注入
<bean id="student" class="com.q.pojo.student">
<!-- 第一种方式:常量注入 这是最基本的常量注入-->
<property name="name" value="leslie"/>
</bean>
(这里注入的是一个值,是最常用的方式)
测试:
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
student student = (student) context.getBean("student");
System.out.println(student.toString());
}
}
测试结果
student{name='leslie', address=null, books=null, hobbies=null, card=null, games=null, info=null, wife='null'}
进程已结束,退出代码0
第二种:
<!-- 第二种方式:Bean方式注入 也就是把一个对象注入到里面,要使用引用-->
<property name="address" ref="address"/>
<bean id="address" class="com.q.pojo.Address">
<property name="address" value="东莞"/>
</bean>
注意点:这里的值是一个引用,ref
第三种:
<!-- 第三种方式:数组注入-->
<property name="books">
<array>
<value>java</value>
<value>linux</value>
<value>java-web</value>
</array>
</property>
第四种:
<!--第四种方式:list-->
<property name="hobbies">
<list>
<value>听歌</value>
<value>看电影</value>
<value>写代码</value>
<value>打球</value>
</list>
</property>
第五种:
<!-- 第五种方式:map注入 用键值对的方式存值-->
<property name="card">
<map>
<entry key="身份证" value="1231456451321315656"/>
<entry key="银行卡" value="124545455651"/>
<entry key="学生卡" value="45456464564455"/>
</map>
</property>
第六种:
<!-- 第六种方式:set方式注入-->
<property name="games">
<set>
<value>王者荣耀</value>
<value>cf</value>
<value>qq飞车</value>
</set>
</property>
第七种:
<!-- 第七种: noll值注入-->
<property name="wife">
<null/>
</property>
第八种:
<!-- 第八种: Properties 注入-->
<property name="info">
<!-- 支柱-->
<props>
<prop key="学号">201821411</prop>
<prop key="身高">1.90</prop>
<prop key="年龄">20</prop>
</props>
</property>
</bean>
测试结果:
student{name='leslie', address=Address{address='东莞'},
books=[java, linux, java-web], hobbies=[听歌, 看电影, 写代码, 打球],
card={身份证=1231456451321315656, 银行卡=124545455651, 学生卡=45456464564455},
games=[王者荣耀, cf, qq飞车], info={学号=201821411, 年龄=20, 身高=1.90}, wife='null'}
进程已结束,退出代码0