set方式注入
【环境】
Student类:
代码如下:
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
}
Address类:
代码如下:
public class Address {
private String address;
}
applicationContext.xml:
代码如下:
<bean id="address" class="com.nysy.pojo.Address">
<property name="address" value="China"/>
</bean>
<bean id="student" class="com.nysy.pojo.Student">
<!--普通值注入,使用value-->
<property name="name" value="zhangsan"/>
<!--bean注入,使用ref-->
<property name="address" ref="address"/>
<!--数组注入-->
<property name="books">
<array>
<value>红楼梦</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!--List注入-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>看电影</value>
<value>敲代码</value>
</list>
</property>
<!--Map注入-->
<property name="card">
<map>
<entry key="身份证" value="1111111111111"></entry>
<entry key="银行卡" value="2222222222222222"></entry>
</map>
</property>
<!--set注入-->
<property name="games">
<set>
<value>LOL</value>
<value>COC</value>
<value>BOB</value>
</set>
</property>
<!--null值注入-->
<property name="wife">
<null/>
</property>
<!--Properties注入-->
<property name="info">
<props>
<prop key="学号">20631920202</prop>
<prop key="姓名">涂涂</prop>
<prop key="性别">男</prop>
</props>
</property>
</bean>
</beans>
测试
代码如下:
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
Student student= (Student) context.getBean("student");
System.out.println(student.toString());
}
输出结果
Student{
name=‘zhangsan’,
address=Address{address=‘China’},
books=[红楼梦, 水浒传, 三国演义],
hobbys=[听歌, 看电影, 敲代码],
card={身份证=1111111111111, 银行卡=2222222222222222},
games=[LOL, COC, BOB],
wife=‘null’,
info={学号=20631920202, 性别=男, 姓名=涂涂}
}
总结
以上是我在学习spring过程中的个人总结。