p命名空间简化属性依赖注入之setter方法

时间:2022-12-16 17:01:10

 为了简化setter方法,之前通过<property>进行注入,p命名使用属性,<bean id="" class=""  p:属性名="普通值"  p:属性名-ref="引用值">。不过这种方法在企业级开发中用的比较少。


如图所示,在实现p命名空间之前,要做一点事情。前面p必选,后面p可以改成别的名字。

p命名空间简化属性依赖注入之setter方法


来两份Bean

public class address 
{
private String name;
private String tel;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
@Override
public String toString() {
return "address [name=" + name + ", tel=" + tel + "]";
}
}

public class person {	private String name;	private address homeAddress;	private address companyAddress;		public String getName() {		return name;	}	public void setName(String name) {		this.name = name;	}	public address getHomeAddress() {		return homeAddress;	}	public void setHomeAddress(address homeAddress) {		this.homeAddress = homeAddress;	}	public address getCompanyAddress() {		return companyAddress;	}	public void setCompanyAddress(address companyAddress) {		this.companyAddress = companyAddress;	}	@Override	public String toString() {		return "person [name=" + name + ", homeAddress=" + homeAddress				+ ", companyAddress=" + companyAddress + "]";	}	}


我们重点关注xml配置。

<!-- 
p命名空间
企业级开发用的比较少
-->
<bean id="homeaddressID" class="com.canyugan.setter.address"
p:name="中环村"
p:tel="1816604">
</bean>
<bean id="companyaddressID" class="com.canyugan.setter.address"
p:name="北京*"
p:tel="123456">
</bean>
<bean id="personID"
class="com.canyugan.setter.person"
p:name="参与感"
p:homeAddress-ref="homeaddressID"
p:companyAddress-ref="companyaddressID">
</bean>


对比不使用p命名空间的配置方法:

	<bean id="homeaddressID" class="com.canyugan.setter.address">
<property name="name" value="中关村"></property>
<property name="tel" value="1816604"></property>
</bean>
<bean id="companyaddressID" class="com.canyugan.setter.address">
<property name="name" value="北京*"></property>
<property name="tel" value="123456"></property>
</bean>
<bean id="personID" class="com.canyugan.setter.person">
<property name="name" value="参与感"/>
<property name="homeAddress" ref="homeaddressID"/>
<property name="companyAddress" ref="companyaddressID"/>
</bean>


是不是看不出来有什么优化?对,企业级开发用的少,有些技术狂人就是喜欢倒腾你不会的东西,所以,我们知道有这个东西就可以。