1、通過引入P名稱空間來完成屬性的注入
(1)寫法
普通屬性:p : 屬性名 = "值"
對象屬性: p :屬性名-ref="值"
(2)注入普通屬性
a、引入p名稱空間的頭
b、使用p名稱空間
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Spring的屬性注入的方式 -->
<!-- 構造方法的方式 -->
<!-- set方法方式符注入 -->
<!-- <bean id="car2" class="com.itzheng.spring.demo4.Car2">
<property name="name" value="奔馳"></property>
<property name="price" value="1000000"></property>
</bean> -->
<!-- 改爲p名稱空間的方式 -->
<!-- set方法方式符注入 -->
<bean id="car2" class="com.itzheng.spring.demo4.Car2" p:name="奇瑞QQ" p:price="30000"></bean>
</beans>
package com.itzheng.spring.demo4;
/*
* set方法的屬性注入
*/
public class Car2 {
private String name;
private Double price;
public void setName(String name) {
this.name = name;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Car2 [name=" + name + ", price=" + price + "]";
}
}
@Test
public void demo5() {
// 創建工程
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
// 獲得到對應XML當中的對象
// 獲得到對應XML當中的對象
Car2 car2 = (Car2) applicationContext.getBean("car2");
System.out.println(car2);
}
(3)注入對象
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Spring的屬性注入的方式 -->
<!-- 改爲p名稱空間的方式 -->
<!-- set方法方式符注入 -->
<bean id="car2" class="com.itzheng.spring.demo4.Car2" p:name="奇瑞QQ" p:price="30000"></bean>
<!-- set方法去注入對象類型的屬性
<bean id="employee" class="com.itzheng.spring.demo4.Employee">
value是用來設置普通類型的值。ref是用來設置其他類的id 或者name
<property name="name" value="張三"/>
<property name="car2" ref="car2"/>
</bean> -->
<bean id="employee" class="com.itzheng.spring.demo4.Employee" p:name="李四" p:car2-ref="car2"></bean>
</beans>
package com.itzheng.spring.demo4;
public class Employee {
private String name;
private Car2 car2;
public void setName(String name) {
this.name = name;
}
public void setCar2(Car2 car2) {
this.car2 = car2;
}
@Override
public String toString() {
return "Employee [name=" + name + ", car2=" + car2 + "]";
}
}
測試