Spring bean賦值的幾種方式

學習Java的人,沒有對Spring這個大名鼎鼎的依賴注入框架陌生的。Spring是一個輕量級的實現了AOP功能的IOC框架,在Java的Web開發中充當着頂樑柱的做用。本文章主要說說在Spring的配置文件中,爲Spring的Bean對象傳值的幾種方式。java

在Spring中,有三種方式注入值到 bean 屬性。spring

  • 正常的方式
  • 快捷方式
  • 「p」 模式

下面就這三種傳值方式,作一個簡短的示例和說明。框架

如今有一個Java類叫Person,詳細的代碼以下:學習

package test;

public class Person {

    private String name;
    private int age;

    /**
     * @return the name
     */
    public String getName() {
	return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
	this.name = name;
    }

    /**
     * @return the age
     */
    public int getAge() {
	return age;
    }

    /**
     * @param age
     *            the age to set
     */
    public void setAge(int age) {
	this.age = age;
    }

}

Person類有兩個屬性,分別是name和age,下面將用Spring爲Person類的屬性注入值。this

一、正常方式code

在property標籤中加入value子標籤,而且爲value子標籤賦值,而且加上property結束標籤xml

<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="Person" class="com.test.Person">
		<property name="name">
			<value>jack</value>
		</property>
		<property name="age">
			<value>21</value>
		</property>
	</bean>
</beans>

二、快捷方式對象

添加value屬性而且爲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="Person" class="com.test.Person">
		<property name="name" value="jack" />
		<property name="age" value="21" />
	</bean>
	
</beans>

三、P模式get

經過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="Person" class="com.test.Person" 
             p:name="jack" p:age="21" />
	
</beans>

須要提醒的是,若是使用P模式傳值,須要添加一個xmlns標籤,到XML的頭部。須要在Spring Bean的配置文件頭加上xmlns:p=」http://www.springframework.org/schema/p"

以上三種傳值方式,沒有什麼重要的區別,這幾種方式均可以隨意配置,可是爲了可維護性和代碼的整潔性,我建議開發人員仍是選擇一個固定的傳值方式,這樣便於項目的管理。

相關文章
相關標籤/搜索