本文共 2941 字,大约阅读时间需要 9 分钟。
欢迎进入《一起学spring》系列博文第二篇,
我们接着上一篇博文'我的第一个spring程序--简单粗暴易懂',我们讲到spring的依赖注入中的设值注入,所谓的设值注入,就是让spring容器使用setter方式来帮我们实例化相关对象,是相对“构造方法”注入来说的。我们还是采用对比的方式,用实例来说话。
一、设值注入:
1、这是不用spring的情况:
我们先来写两个类,具体见下面代码:
package com.huai.first;public class Book { public void doBookPrint(){ System.out.println("method -- doBookPrint"); }}
package com.huai.first;public class Student { private Book book; public void setBook(Book book){ this.book = book; } public void doStudentPrint(){ this.book.doBookPrint(); }}接下来我想让代码跑起来,好,我们来写一个main函数:
package com.huai.first;public class MainTest { public static void main(String[] args) { Student stu = new Student(); Book book = new Book(); stu.setBook(book); stu.doStudentPrint(); }}好,搞定。
(注意,在main函数中我们的对象都是通过new的方式实例化的,下面,我们使用spring框架,直接从spring容器中获取对象,因为spring容器已经帮我们实例化好了)
2、这是使用spring的情况:
我们同样需要写两个类:Student和Book,代码和上面一样。只是main函数不同
package com.huai.first;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Student stu = context.getBean(Student.class); stu.doStudentPrint(); }}分析一下上面这个main函数:
(1)、首先,我们肯定要创建一个spring容器
(2)、从spring容器中获取我们想要的对象stu
为什么不获取book对象,然后通过stu.setBook(book);的方式写呢?回答是:你这样的想法是没有问题的,完全行得通。而我上面这样子写也是可以的。
在Student类中,book作为Student的属性,所以需要在某个地方实例化book对象,否者会报空指针异常。可是,上面的代码中并没有看到实例化book对象的语句。为什么?具体原因等到我们看完我们的配置文件之后再讨论。
分析spring配置文件:
(1)、配置两个<bean>,目的是告诉spring容器,帮我实例化这两个类的对象,也就是student和book。
(2)、实例化两个对象之后,再帮忙把book对象作为Student类的一个属性传进去。对应的是:<property name="book" ref="bookID">(注:这里传进去的是book对象)
(ref表示:reference,引用的意思;其中name=“book”中的book需和Student类中的book属性名一样)
二、构造注入:
同样地,我们写两个类:
package com.huai.first;public class Book { public void doBookPrint(){ System.out.println("method -- doBookPrint"); }}
package com.huai.first;public class Student { private Book book; // public void setBook(Book book){// this.book = book;// } public Student(Book book){ this.book = book; } public void doStudentPrint(){ this.book.doBookPrint(); }}注:Student类中增加了一个有参的构造方法;setBook方法可以保留的。
下面我们写一个main函数:(它和上面的设值注入的main函数相同)
package com.huai.first;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Student stu = context.getBean(Student.class); stu.doStudentPrint(); }}看看配置文件:
请注意<constructor-arg>属性,name=“book”中的book是和Student类中的构造函数中的形参对应的。
分析:
设值注入:通过无参的构造方法来示例话,通过setter方法初始化属性。
构造注入:通过有参的构造函数实例化和初始化。
思考:似乎,使用spring框架比不使用更加麻烦了!我们这样使用spring-framework有必要吗?
回答:使用spring框架的目的不是本博文所涉及的内容,这里只是跟大家谈谈spring-framework的用法。谢谢
如果需要下载spring的jar包,请找上一篇博文最下面的链接
转载地址:https://liangyihuai.blog.csdn.net/article/details/48895059 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!