依赖注入的方法及如何使用

您所在的位置:网站首页 描述spring依赖注入的工作机制 依赖注入的方法及如何使用

依赖注入的方法及如何使用

2023-09-01 04:12| 来源: 网络整理| 查看: 265

//代码来自知乎摘抄

依赖:一个类的属性是对象的时候,称为依赖。

注入:给对象(类的某个属性)赋值。

依赖注入(将被依赖的对象注入给依赖类)有三种方式:构造函数注入、setter方法注入、接口注入

构造函数注入:

将被依赖对象通过构造函数的参数注入给依赖对象,在依赖对象初始化的时候实现注入。

在对象初始化完成后就获得了可以使用的对象。依赖对象的属性值,就一直是被依赖对象的值了,建立了长期的关系。 当需要注入的对象很多时,构造器的参数列表会很长通过反射构造对象的时候,构造方法无法被继承,无法设置默认值。不够灵活。在有很多中注入方式的时候,每种方式只需注入指定几个依赖,(对于非必须的依赖处理)那么就需要提供多个重载的构造函数,比较麻烦。 //从其他人的知乎摘抄 public class StupidStudent { private SmartStudent smartStudent; public StupidStudent(SmartStudent smartStudent) { this.smartStudent = smartStudent; } public doHomewrok() { smartStudent.doHomework(); System.out.println("学渣抄作业"); } } public class StudentTest { public static void main(String[] args) { SmartStudent smartStudent = new SmartStudent(); StupidStudent stupidStudent = new StupidStudent(smartStudent); stupidStudent.doHomework(); } } setter方法注入

在依赖类中有一个setter函数,该函数实现将被依赖对象赋值为依赖对象

比较灵活,可以有选择性地注入需要的对象这种方式学霸和学渣只是暂时的合作关系,如果学渣赖上了另一个学霸(调用set()方法传入了另一个对象),那么学渣和学霸的合作关系就结束了。 在依赖对象初始化完成后,它的需要注入的属性值还未赋值,所以暂时不可使用 public class StupidStudent { private SmartStudent smartStudent; public void setSmartStudent(SmartStudent smartStudent) { this.smartStudent = smartStudent; } public doHomewrok() { smartStudent.doHomework(); System.out.println("学渣抄作业"); } } public class StudentTest { public static void main(String[] args) { SmartStudent smartStudent = new SmartStudent(); StupidStudent stupidStudent = new StupidStudent(); stupidStudent.setSmartStudent(smartStudent); stupidStudent.doHomework(); } }

 

接口注入

依赖类必须要实现指定的接口,然后实现该接口中的一个函数,该函数就是用于依赖注入。该函数的参数就是要注入的对象。

采用这种注入方式,学渣只是在做作业时,才临时抱佛脚地找一下学霸。接口注入中,接口的名字、函数的名字都不重要,只要保证函数的参数是要注入的对象类型即可。 侵入行太强,不建议使用。(如果类A要使用别人提供的一个功能,若为了使用这功能,需要在自己的类中增加额外的代码,这就是侵入性。) public class StupidStudent { public doHomewrok(SmartStudent smartStudent) { smartStudent.doHomework(); System.out.println("学渣抄作业"); } }

 

public class StudentTest { public static void main(String[] args) { SmartStudent smartStudent = new SmartStudent(); StupidStudent stupidStudent = new StupidStudent(); stupidStudent.doHomework(smartStudent); } }

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3