p-namespace(名稱空間) 讓你使用 bean 元素的屬性(而不是巢狀的
基本使用示例:
- 實體類:
public class Dog {
private String name;
private int age;
private Date birth;
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
", birth=" + birth +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
}
- spring配置檔案,預設的spring配置檔案是不包含的p空間,需要單獨新增:xmlns:p="http://www.springframework.org/schema/p"
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用p名稱空間-->
<bean id="dogBean" class="com.powernode.spring6.bean.Dog"
p:name="小花" p:age="3" p:birth-ref="birthBean"/>
<bean id="birthBean" class="java.util.Date"/>
<!--使用傳統標準的XML格式-->
<!--<bean id="dogBean" class="com.powernode.spring6.bean.Dog">
<property name="name" value="小花"></property>
<property name="age" value="3"></property>
<property name="birth" ref="birthBean"></property>
</bean>-->
</beans>
- 測試
@Test
public void testP(){
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring-p.xml");
Dog dogBean = classPathXmlApplicationContext.getBean("dogBean", Dog.class);
System.out.println(dogBean);
}
輸出: Dog
Spring 3.1中引入的c名稱空間允許配置構造器引數的內聯屬性,而不是巢狀的 constructor-arg 元素。
引用官網案例:
<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="beanTwo" class="x.y.ThingTwo"/>
<bean id="beanThree" class="x.y.ThingThree"/>
<!-- traditional declaration with optional argument names -->
<bean id="beanOne" class="x.y.ThingOne">
<constructor-arg name="thingTwo" ref="beanTwo"/>
<constructor-arg name="thingThree" ref="beanThree"/>
<constructor-arg name="email" value="something@somewhere.com"/>
</bean>
<!-- c-namespace declaration with argument names -->
<bean id="beanOne" class="x.y.ThingOne" c:thingTwo-ref="beanTwo"
c:thingThree-ref="beanThree" c:email="something@somewhere.com"/>
</beans>
- 對於建構函式引數名稱不可用的罕見情況(通常是位元組碼編譯時沒有debug資訊),你可以使用回退到引數索引(下標),如下所示。
<!-- c-namespace index declaration -->
<bean id="beanOne" class="x.y.ThingOne" c:_0-ref="beanTwo" c:_1-ref="beanThree"
c:_2="something@somewhere.com"/>