您的位置:首页 > 编程语言 > Java开发

Spring bean赋值的几种方式

2016-08-24 00:00 381 查看
学习Java的人,没有对Spring这个大名鼎鼎的依赖注入框架陌生的。Spring是一个轻量级的实现了AOP功能的IOC框架,在Java的Web开发中充当着顶梁柱的作用。本文章主要说说在Spring的配置文件中,为Spring的Bean对象传值的几种方式。

在Spring中,有三种方式注入值到 bean 属性。

正常的方式

快捷方式

“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类的属性注入值。

1、正常方式

在property标签中加入value子标签,并且为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="Person" class="com.test.Person">
<property name="name">
<value>jack</value>
</property>
<property name="age">
<value>21</value>
</property>
</bean>
</beans>

2、快捷方式

添加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>

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="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"

以上三种传值方式,没有什么重要的区别,这几种方式都可以随意配置,但是为了可维护性和代码的整洁性,我建议开发人员还是选择一个固定的传值方式,这样便于项目的管理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息