如何注入值到Spring bean屬性

在Spring中,有三種方式注入值到 bean 屬性。
  • 正常的方式
  • 快捷方式
  • “p” 模式
看到一個簡單的Java類,它包含兩個屬性 - name 和 type。稍後將使用Spring注入值到這個 bean 屬性。
package com.xuhuhu.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.xuhuhu.common.FileNameGenerator">
		<property name="name">
			<value>zaixian</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.xuhuhu.common.FileNameGenerator">
		<property name="name" value="zaixian" />
		<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.xuhuhu.common.FileNameGenerator"
             p:name="zaixian" p:type="txt" />

</beans>
記住聲明 xmlns:p=”http://www.springframework.org/schema/p" 在Spring XML bean配置檔。

總結

這些方法的使用完全是基於個人喜好,也不會影響注入bean屬性的值。

上一篇: Spring Bean引用例子 下一篇: Spring bean加載多個配置檔