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

Spring:设值注入用法

2016-06-02 20:39 387 查看
  首先明确Java中什么是依赖关系:

  类A依赖类B的意思是,如果A的对象要完成某一操作,必须使用B的对象的某些操作来帮忙,才能完成。简言之,B作为A的某个方法的方法参数存在。如下:

class A{
public void f(B b){

}
}
class B{

}


 Spring的作用就是管理JavaEE中的各个组件,并把所有的Java对象都称之为Bean,因此完全可以把任何的Java类都部署在Spring中,但是Java类中必须有相应的构造器。 

  设值注入通过<property/>元素驱动Spring执行setter方法,为参数传入参数值,而Java类的成员变量又可以是各种数据类型,除了基本的数据类型外,还可以是其他Java实例,也可以是Spring容器中其他Bean实例,甚至是Java集合,数组等,因此Spring允许如下元素为setter方法、构造器参数指定参数值。

1:value  用于注入基本数据类型

2:ref   当注入的成员变量属于Sping容器中的其他Bean实例则应使用ref元素。

3:bean  称之为注入嵌套Bean,当某个Bean所依赖的Bean不想被容器访问,则可以使用嵌套Bean,其本质与ref一样

4:list、set、map、props 当注入的成员变量属于集合时则使用这些元素。

  Spring可以为任何Java对象注入任何类型的属性,只要该Java对象为该属性提供了相应的setter方法,Spring就是通过该方法,完成的相应赋值和注入。

一:当注入普通属性时—————value元素的使用

1:我们定义一个Bean实例的实现类 Test.java

package com.mao.test;

public class Test {
private String userName;
//为Spring容器注入普通属性提供setter方法
public void setUserName(String userName) {
this.userName = userName;
}

public void input(){
System.out.println("正在调用setUserName()方法,传入的参数为:"userName);
}
}


该类中声明了一个普通属性 userName,并提供了set方法,Spring容器也正是通过该方法完成的属性注入。

2:我们的配置文件beans.xml

<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!-- 创建一个id为test的Bean实例 -->
<bean id="test" class="com.mao.test.Test">
<!-- 通过setName方法为参数赋值  参数值为VipMao -->
<property name="userName" value="VipMao"></property>
</bean>
</beans>

说一下配置文件,我们定义了一个id为test的Bean实例,他的实现类是com.mao.test包下的Test.java(也就是上面那个程序),然后<bean>内定义了个<property>标签,name属性的值表示调用哪个属性的set方法进行注入赋值,value属性得值表示传入的参数是什么。上面的配置文件就是:有一个test的Bean实例,然后Spring容器通过setUserName方法,将VipMao参数注入给userName属性。咱们仅仅需要提供一个setter方法,然后"坐等"Spring通过该setter方法完成赋值并注入给userName属性。

3:我们的测试类 TestManager.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestManager {
public static void main(String[]args){
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
//获取Bean实例
Test t=(Test) ctx.getBean("test");
//执行input方法
t.input();
}
}

4:执行结果

正在调用setUserName()方法,传入的参数为:VipMao

  可以看出,在主程序测试类中我们并没有通过代码设置name属性的值,而是<property/>元素驱动Spring容器通过相应的set方法,将value元素的值注入给属性,但是前提是:

(1):在Bean 实例中提供了相应的setter方法(Spring容器通过该方法注入)

(2):该属性为普通属性(上面的name属性为String型)

二:注入的属性为Spring中的另一个Bean属性----ref元素的使用

如果我们在一个Bean实例中的一个方法中使用了另一个Bean实例,也就是上面说的依赖关系,或者说需要为Bean设置的属性值是容器中的另一个Bean的实例,则应该使用ref元素。如下例子:

1:Bean实例 Person.java

package com.mao.test;

public class Person {
private Chinese chinese;

public Person() {
System.out.println("----------Spring容器通过调用无参构造函数创建Bean实例----------");
}

public void setChinese(Chinese chinese) {
this.chinese = chinese;
}
public void useChinese(){
System.out.println(chinese.say());
}
}
上面声明了一个Chinese属性,并提供了setter方法,在Person类useChinese()方法中用到了chinese实例,接下来我们看一下Spring容器怎么通过ref元素将Chinese实例注入给chinese

2:我们的配置文件beans.xml

<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!-- 定义chinesePerson Bean实例,实现类Chinese类 -->
<bean id="chinesePerson" class="com.mao.test.Chinese"></bean>
<!-- 创建一个person Bean 实现类Person类-->
<bean id="person" class="com.mao.test.Person">
<!-- 驱动调用person的setChinese()方法,将容器中的chinesePerson Bean实例作为传入参数 -->
<property name="chinese" ref="chinesePerson"></property>
</bean>
</beans>
配置文件中先定义了一个chinesePerson Bean实例,实现类是Chinese类,然后定义了一个person的Bean实例,<property>内的name和ref元素值就是:通过Person类的setChinese方法将容器中的chinesePerson Bean实例作为参数注入给chinese,这就相当于执行了 Chinese chinese=new
Chinese(); 只不过这个过程是Spring通过set方法实现的。

3:被引用的chinese Bean实例 Chinese.java

package com.mao.test;

public class Chinese {
public String say(){
return"我是中国人";
}
}<span style="font-size:14px;">
</span>


4:测试程序 PersonManager.java

public class PersonManager {
public static void main(String[]args){
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
//获取person Bean实例
Person p=(Person) ctx.getBean("person", Person.class);
p.useChinese();
}
}


5:输出结果:



可以看出,我们并没有在主程序中通过new的方式创建Chinese对象,这一切都是Spring容器通过ref引用chinesePerson的Bean实例,将该实例作为参数通过setter方法完成赋值和注入,通过输出结果我们也可以发现Spring容器是通过无参数构造器来创建Bean实例的

三:注入嵌套Bean

   当某个Bean所依赖的Bean不想被Spring容器直接访问时,例如上一个例子person的Bean实例需要依赖chinese的Bean实例,则可以使用嵌套Bean,将chinese的Bean实例嵌套进person的Bean实例,因为嵌套Bean实例的本质是和ref引用容器是一样的,因此我们完成上一个例子,仅需稍微修改一下配置文件beans.xml

<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!-- 创建一个person Bean 实现类Person类-->
<bean id="person" class="com.mao.test.Person">
<!-- 驱动调用person的setChinese()方法,将容器中的chinesePerson Bean实例作为传入参数 -->
<property name="chinese">
<!-- 定义chinesePerson Bean实例,实现类Chinese类 -->
<bean class="com.mao.test.Chinese"></bean>
</property>
</bean>
</beans>

如上,将chinese的Bean实例嵌套到person Bean的<property>子元素,那么该chinese Bean就仅仅作为setter注入的参数,由于不需要容易访问该Bean,因此也就不需要指定id属性。

其他代码不用改,运行结果依旧:



四:注入集合值

  当我们需要注入集合值时,我们则可以使用集合元素<list/><set/><map/><props>分别为List、Set、Map、和Properties的集合设置属性值,如下:

1:Chinese.java

package com.mao.collection;

import java.util.*;

public class Chinese implements Person{

// 下面是系列集合类型的成员变量
private List<String> schools;
private Map scores;
private Map<String , Axe> phaseAxes;
private Properties health;
private Set axes;
private String[] books;

public Chinese()
{
System.out.println("Spring实例化主调bean:Chinese实例...");
}

// schools的setter方法
public void setSchools(List schools)
{
this.schools = schools;
}
// scores的setter方法
public void setScores(Map scores)
{
this.scores = scores;
}
// phaseAxes的setter方法
public void setPhaseAxes(Map<String , Axe> phaseAxes)
{
this.phaseAxes = phaseAxes;
}
// health的setter方法
public void setHealth(Properties health)
{
this.health = health;
}
// axes的setter方法
public void setAxes(Set axes)
{
this.axes = axes;
}
// books的setter方法
public void setBooks(String[] books)
{
this.books = books;
}

// 访问上面全部的集合类型的成员变量
public void test()
{
System.out.println("----开始输出List集合--------");
Iterator it=schools.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println("--------开始输出Map集合---------- ");
System.out.println(scores);
System.out.println("---------开始遍历<String,Axe集合>----------");
System.out.println(phaseAxes);
System.out.println("---------开始遍历Properties----------");
System.out.println(health);
System.out.println("---------开始遍历Set集合----------");
Iterator itSet=axes.iterator();
while(itSet.hasNext()){
System.out.println(itSet.next());
}
System.out.println("-----开始遍历Array数组集合-------------");
System.out.println(java.util.Arrays.toString(books));
for(String array:books){
System.out.println(array);
}

}

}

2:下面分别用<list/><set/><map/><props>来在配置文件beans.xml中为集合设置参数值。

<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <bean id="steelAxe" class="com.mao.collection.SteelAxe"></bean>
<bean id="stoneAxe" class="com.mao.collection.StoneAxe"></bean>
<bean id="chinese" class="com.mao.collection.Chinese">
<property name="schools">
<list>
<value>菜鸟学院</value>
<value>大牛学院</value>
<value>大神学院</value>
</list>
</property>
<property name="scores">
<map>
<entry key="语文" value="86"/>
<entry key="数学" value="95"/>
<entry key="英语" value="100"/>
</map>
</property>
<property name="phaseAxes">
<map>
<entry key="原始社会" value-ref="stoneAxe"/>
<entry key="农业社会" value-ref="steelAxe"/>
</map>
</property>
<property name="health">
<props>
<prop key="血压">正常</prop>
<prop key="身高">175</prop>
</props>
</property>
<property name="axes">
<!-- 为调用setAxes()方法配置Set集合作为参数值 -->
<set>
<!-- 每个value、ref、bean..都配置一个Set元素 -->
<value>普通的字符串</value>
<bean class="com.mao.collection.SteelAxe"/>
<ref bean="stoneAxe"/>
<!-- 为Set集合配置一个List集合作为元素 -->
<list>
<value>20</value>
<!-- 再次为List集合配置一个Set集合作为元素 -->
<set>
<value type="int">30</value>
</set>
</list>
</set>
</property>
<property name="books">
<list>
<value>Java从入门到精通</value>
<value>轻量级JavaEE企业应用实战</value>
<value>经典JavaEE企业应用实战</value>
</list>
</property>
</bean>
<bean id="example" class="com.mao.fuhe.Example">
<property name="person.name" value="VipMao"></property>
</bean>
</beans>


Spring容器也是通过<property>的name属性调用相应的setter方法,完成相应集合的赋值注入。

3:主程序 TestManager.java

package com.mao.collection;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestManager {
public static void main(String[]args){
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
Chinese chinese=(Chinese) ctx.getBean("chinese");
chinese.test();
}
}

4:运行结果:



总结:

Spring框架本质就是通过xml配置文件来驱动Java代码,当程序要调用setter方法时,总需要传入参数值,随着参数值不同,Spring配置文件也要改变:

1:形参类型是基本数据类型:String ,日期等  使用value

2:形参类型是符合类型:使用ref或者嵌套Bean

3:形参类型是集合,使用<list/><set/><map/><props>来注入集合参数值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息