Spring 专题
专题目录
您的位置:java > Spring专题 > 如何注入值到Spring bean属性
如何注入值到Spring bean属性
作者:--    发布时间:2019-11-20
在spring中,有三种方式注入值到 bean 属性。
  • 正常的方式
  • 快捷方式
  • “p” 模式
看到一个简单的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>
记住声明 xmlns:p=”http://www.springframework.org/schema/p" 在spring xml bean配置文件。

总结

这些方法的使用完全是基于个人喜好,也不会影响注入bean属性的值。

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册