1.通过set方法注入
1.1.普通值注入
<bean id="student" class="com.sun.pojo.Student">
<property name="name" value="小明"/>
</bean>
1.2.对象类型注入
Student类:
Address类:
<bean id="address1" class="com.sun.pojo.Address">
<property name="address" value="西安"/>
</bean>
<bean id="student" class="com.sun.pojo.Student">
<property name="name" value="小明"/>
<property name="address" ref="address1"/>
</bean>
1.3.数组类型注入
<!--数组类型注入-->
<property name="books">
<array>
<value>水浒传</value>
<value>西游记</value>
</array>
</property>
1.4.集合类型注入
<!--集合类型注入-->
<property name="hobbies">
<list>
<value>听歌</value>
<value>看电影</value>
</list>
</property>
1.5.Map类型注入
<!--Map注入-->
<property name="card">
<map>
<entry key="身份证" value="123456789"/>
<entry key="学生证" value="102456551"/>
</map>
</property>
1.6.Set类型注入
<!--Set注入-->
<property name="games">
<set>
<value>王者荣耀</value>
<value>lol</value>
</set>
</property>
1.7.null值注入
<!--null-->
<property name="wife">
<null/>
</property>
1.8.Properties类型注入
<!--Properties-->
<property name="info">
<props>
<prop key="用户名">小明</prop>
<prop key="密码">123456</prop>
</props>
</property>
2.通过p命名空间注入
本质上还是使用set方式来注入的,其形式只是简化了一些
在使用之前得有添加一条配置,如下:
xmlns:p="http://www.springframework.org/schema/p"
2.1.测试
bean文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.sun.pojo.Address" p:address="西安"/>
</beans>
测试类:
@Test
public void testAddress(){
ApplicationContext context = new ClassPathXmlApplicationContext("addressBeans.xml");
Address address = (Address) context.getBean("address");
System.out.println(address.toString());
}
结果:
3.通过c命名空间注入
本质上是使用有参构造来进行注入的
在使用之前得有添加一条配置,如下:
xmlns:c="http://www.springframework.org/schema/c"
3.1.测试
bean文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address2" class="com.sun.pojo.Address" c:address="西安"/>
</beans>
测试类:
@Test
public void testAddress(){
ApplicationContext context = new ClassPathXmlApplicationContext("addressBeans.xml");
Address address = (Address) context.getBean("address2");
System.out.println(address.toString());
}
结果: