学习Java的人,没有对Spring这个大名鼎鼎的依赖注入框架陌生的。Spring是一个轻量级的实现了AOP功能的IOC框架,在Java的Web开发中充当着顶梁柱的做用。本文章主要说说在Spring的配置文件中,为Spring的Bean对象传值的几种方式。java
在Spring中,有三种方式注入值到 bean 属性。spring
下面就这三种传值方式,作一个简短的示例和说明。框架
如今有一个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"
以上三种传值方式,没有什么重要的区别,这几种方式均可以随意配置,可是为了可维护性和代码的整洁性,我建议开发人员仍是选择一个固定的传值方式,这样便于项目的管理。