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

前端之家收集整理的这篇文章主要介绍了《Pro Spring》学习笔记之依赖解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我们有如下两个类:

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

原文链接:https://www.f2er.com/javaschema/288222.html

猜你在找的设计模式相关文章