【Spring学习笔记三】-依赖注入的两种方式
发布时间:2020-12-14 02:10:36 所属栏目:百科 来源:网络整理
导读:依赖注入通常有两种方式:设值注入和构造注入。设值注入,即Spring容器使用属性的setter方法来注入被依赖的实例。构造注入,即Spring容器使用构造器来注入被依赖的实例。 一、设值注入 设值注入是指Spring容器使用属性的setter方法来注入被依赖的实例。这种
依赖注入通常有两种方式:设值注入和构造注入。设值注入,即Spring容器使用属性的setter方法来注入被依赖的实例。构造注入,即Spring容器使用构造器来注入被依赖的实例。 一、设值注入 设值注入是指Spring容器使用属性的setter方法来注入被依赖的实例。这种注入方式简单、直观,因而在Spring的依赖注入里大量使用。还是以上一篇博客中讲到的人和斧子为例。 首先,定义人和斧子接口。
public interface Person { //定义一个使用斧子的方法 public void useAxe(); } public interface Axe { public String chop(); } 下面是Person实现类的代码:
public class Chinese implements Person { private Axe axe; public void setAxe(Axe axe) { this.axe = axe; } public void ueAxe() { System.out.println(axe.chop()); } } 下面是Axe的实现类
public class StoneAxe implements Axe { public String chop() { return “石斧砍柴好慢”; } } bean配置文件如下:
<?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-3.0.xsd"> <bean id="Chinese" class="com.ceshi.service.impl.Chinese"> <property name="axe" value="stoneAxe"/> </bean> <bean id="stoneAxe" class="com.ceshi.service.impl.StoneAxe"> </beans> 下面是主程序的清单: public class BeanTest { public static void main (String [] args) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext(“bean.xml”); Person p = ctx.getBean(“Chinese”,Person.class); p.useAxe(); } } 代码运行后,输出:石斧砍柴好慢。 主程序调用Person的useAxe方法来执行,该方法的方法体内需要使用Axe实例,但程序没有任何地方将特定的Person实例和Axe实例耦合在一起。Person实例不仅不需要了解Axe实例的具体实现,甚至无须了解Axe的创建过程。 二、构造注入 构造注入,即Spring容器使用构造器来注入被依赖的实例。还以上面的实例为例,进行简单的修改。 对Chinese类做简单的修改: public class Chinese implements Person { private Axe axe; public Chinese() { } //构造注入所需的带参数的构造器 public Chinese(Axe axe) { this.axe = axe; } public void ueAxe() { System.out.println(axe.chop()); } } 之后,还需要对配置文件进行简单修改。如下: <?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-3.0.xsd"> <bean id="Chinese" class="com.ceshi.service.impl.Chinese"> <constructor-arg ref="stoneAxe"/> </bean> <bean id="stoneAxe" class="com.ceshi.service.impl.StoneAxe"> </beans> 执行结果与设值注入执行结果是一致的。它们的区别在于:创建Person实例中Axe属性的时机不同-设值注入时先通过无参数的构造器创建一个Bean实例,然后调用对应的setter方法注入依赖关系;而构造注入则直接调用有参数的构造器,当Bean实例创建完成后,已经完成了依赖关系的注入。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |