看到一个简单的java类,它包含两个属性 - name 和 type。稍后将使用spring注入值到这个 bean 属性。
package com.h3.common;
public class filenamegenerator
{
private string name;
private string type;
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
public string gettype() {
return type;
}
public void settype(string type) {
this.type = type;
}
}
1.正常方式
在一个“value”标签注入值,并附有“property”标签结束。
<beans xmlns="http://www.springframework.org/schema/beans"
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-2.5.xsd">
<bean id="filenamegenerator" class="com.h3.common.filenamegenerator">
<property name="name">
<value>h3</value>
</property>
<property name="type">
<value>txt</value>
</property>
</bean>
</beans>
2,快捷方式
注入值“value”属性。
<beans xmlns="http://www.springframework.org/schema/beans"
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-2.5.xsd">
<bean id="filenamegenerator" class="com.h3.common.filenamegenerator">
<property name="name" value="h3" />
<property name="type" value="txt" />
</bean>
</beans>
3. “p” 模式
通过使用“p”模式作为注入值到一个属性。
<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-2.5.xsd">
<bean id="filenamegenerator" class="com.h3.common.filenamegenerator"
p:name="h3" p:type="txt" />
</beans>
总结
这些方法的使用完全是基于个人喜好,也不会影响注入bean属性的值。