《Pro Spring》学习笔记之依赖解析

我们有如下两个类:

 

package  ch4_alias;

public   class  Course  {
    
public Course(){
        System.out.println(
"in course");
    }

  
private String courseName;

public String getCourseName() {
    
return courseName;
}


public void setCourseName(String courseName) {
    
this.courseName = courseName;
}

}



package  ch4_alias;

public   class  Student  {
  
private String stuName;
  
private Course stuCourse;
  
public Student(){
      System.out.println(
"in student");
  }

public Course getStuCourse() {
    
return stuCourse;
}

public void setStuCourse(Course stuCourse) {
    
this.stuCourse = stuCourse;
}

public String getStuName() {
    
return stuName;
}

public void setStuName(String stuName) {
    
this.stuName = stuName;
}

}

 我们用如下的方式进行注入

<? xml version="1.0" encoding="UTF-8" ?>
< 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.0.xsd" >
< bean  id ="student"  class ="ch4_alias.Student"   >
< property  name ="stuName" >
    
< value > gaoxiang </ value >
  
</ property >
< property  name ="stuCourse" >
  
< ref  bean ="stuCourse" />
</ property >
</ bean >


< bean  id ="course"  name ="stuCourse"  class ="ch4_alias.Course" >
  
< property  name ="courseName" >
    
< value > shuxu </ value >
  
</ property >
</ bean >
</ beans >

可以发现,spring为我们首先构造了student,然后再构造course,然后把course注入到student的引用对象中

如果使用depends-on="course"

 

<? xml version="1.0" encoding="UTF-8" ?>
< 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.0.xsd" >
< bean  id ="student"  class ="ch4_alias.Student"  depends-on ="course" >
< property  name ="stuName" >
    
< value > gaoxiang </ value >
  
</ property >
< property  name ="stuCourse" >
  
< ref  bean ="stuCourse" />
</ property >
</ bean >


< bean  id ="course"  name ="stuCourse"  class ="ch4_alias.Course" >
  
< property  name ="courseName" >
    
< value > shuxu </ value >
  
</ property >
</ bean >
</ beans >

 

则spring会首先构造course,然后构造student,然后把course注入到student引用对象中

 

实际开发中,并不建议这样强制决定构造顺序,在将spring代码与遗留系统整合时候,可能会用到depends-on

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值