加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 程序设计 > 正文

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

发布时间:2020-05-27 12:02:50 所属栏目:程序设计 来源:互联网
导读:我们有如下两个类: package ch4_alias; public class Course ... { publicCourse()...{ System.out.println(incourse); } privateStringcourseName; publicStringgetCourseName()...{

我们有如下两个类:

package ch4_alias;

public class Course ... {
publicCourse()...{
System.out.println("incourse");
}
privateStringcourseName;

publicStringgetCourseName()...{
returncourseName;
}

publicvoidsetCourseName(StringcourseName)...{
this.courseName=courseName;
}
}


package ch4_alias;

public class Student ... {
privateStringstuName;
privateCoursestuCourse;
publicStudent()...{
System.out.println("instudent");
}
publicCoursegetStuCourse()...{
returnstuCourse;
}
publicvoidsetStuCourse(CoursestuCourse)...{
this.stuCourse=stuCourse;
}
publicStringgetStuName()...{
returnstuName;
}
publicvoidsetStuName(StringstuName)...{
this.stuName=stuName;
}
}

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

<? xmlversion="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/beanshttp://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"

<? xmlversion="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/beanshttp://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

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读