0. Spring 的 控制反转和依赖注入

提起Spring,很多人第一反应就是IOC和AOP。那IOC到底是什么东东?

image.png

IOC(Inversion of Control) 翻译过来叫控制反转。DI(Dependency Injection)翻译过来叫依赖注入。这时候就应该掏出我们的人生三问了。

image.png

控制反转用人话说就是,本来是程序员控制对象初始化,现在程序员不初始化了,把这个工作交给Spring 来干了,也就是把工作反手转给Spring了。不管转给谁,反正我不干,就是反转了。

举个例子:本来程序员要找女朋友需要自己去寻寻觅觅,不期而遇。但现在国家出政策了,要的时候国家给你,而且不止能主动要,你只要提要求,国家还能给你送过来。不信你看这段代码:

@Component // 把自己的单身的情况向国家说明
public class SingleDog {

    @Autowired
    private ApplicationContext applicationContext; // 国家派了专人对接

    public void qinqinbaobaojugaogao1() {
        // 我还没女朋友,给我一个吧
        GirlFriend girlFriend = (GirlFriend) applicationContext.getBean("girlFriend");
        qinqinbaobaojugaogao(girlFriend);
    }
}
@Component // 把自己的单身的情况向国家说明
public class SingleDog {
    @Autowired
    private ApplicationContext applicationContext;

    // 我缺一个女朋友,给我送过来一个吧?
    @Autowired
    private GirlFriend girlFriend;

    public void qinqinbaobaojugaogao() {
        qinqinbaobaojugaogao(this.girlFriend);
    }
}

对比没有Spring的时候,单身狗没有女朋友的时候只能自己new一个。

public class SingleDog {
        public void qinqinbaobaojugaogao(GirlFriend girl) {
        System.out.println("亲亲抱抱举高高");
    }
    public static void main(String[] args) {
        // 我还没女朋友,自己new一个
        GirlFriend girlFriend = new GirlFriend("肤白貌美大长腿");
        SingleDog singleDog = new SingleDog();
        singleDog.qinqinbaobaojugaogao(girlFriend);
    }
}

Spring方式获取对象的时候看不到new了,这就是这两个思想的最大区别,也就是控制反转的思想。

image.png

有同学这时候肯定要问了,也没节省多少代码啊,这不是脱裤子放屁吗?确实,在这个示例中是这样的。

但是如果有一些new过程特别复杂的对象呢?(有这种东西吗?)我们来看一段go代码,这是我第一次使用golang写项目代码,可以提前拿好塑料袋。

// NewSrv 实例化所有业务对象
func NewSrv(r *gin.Engine, viper *viper.Viper) {
	// 实例化client
	appClient := app.NewAppClient(viper.GetString("client.app"))
	accountClient := account.NewDaprAccountClient()
	v5MsgClient := msgClient2.NewMsgClient()
	msgClient := msg.NewMsgClient(viper.GetString("client.msg"))
	fileClient := file.NewFileClient(viper.GetString("client.file"))
	translateClient := translate.NewTranslateClient()
	mqttServiceClient := mqtt.NewMqttServiceClient()

	// repository
	mysqlCfg := new(driver.MysqlDBCfg)
	err := viper.UnmarshalKey("mysql", mysqlCfg)
	if err != nil {
		panic(err)
	}
	db, err := new(driver.DataDriver).InitMysqlDB(mysqlCfg)
	if err != nil {
		panic(err)
	}
	robotRepo := repo.NewRobotRepo(db)
	robotAppRepo := repo.NewRobotAppRepo(db)
	corpAppRepo := repo.NewCorpAppRepo(db)
	robotGidRepo := repo.NewRobotGidRepo(db)
	userAvatarRepo := repo.NewAvatarRepo(db)
	callbackRepo := repo.NewCallbackRepo(db)
	sessViewRepo := repo.NewSessViewRepo(db)

	// cache
	redisClient, err := GetRedisClient(viper.GetString("redis.addr"), viper.GetString("redis.password"), viper.GetInt("redis.db"))
	if err != nil {
		panic(err)
	}
	authTokenCache := &cache.AuthTokenCache{RedisDB: redisClient}

	// 实例化service
	key := viper.GetString("jwt.key")
	signature := viper.GetString("jwt.signature")
	appService := service.NewAppService(appClient)
	robotService := service.NewRobotService(robotRepo, robotAppRepo)
	orgService := service.NewOrgService(
		appService, robotService, accountClient, accountClientImpl, appClient, v5MsgClient, fileClient,
		key, signature, corpAppRepo, robotAppRepo, authTokenCache, userAvatarRepo)
	msgService := service.NewMsgService(msgClient, v5MsgClient, appClient, fileClient, accountClient, robotAppRepo, robotGidRepo)
	callbackService := service.NewCallbackService(orgService, accountClient, callbackRepo, corpAppRepo)
	sessViewService := service.NewSessionViewService(sessViewRepo, msgClient, fileClient, viper.GetString("staticDir"))
	mqttService := service.NewMqttService(mqttServiceClient)

	// 实例化handler
	orgHandler := NewOrgHandler(orgService, msgService)
	msgHandler := NewMsgHandler(msgService)
	appHandler := NewAppHandler(robotService)
	callbackHandler := NewCallbackHandler(callbackService)
	sessionHandler := NewSessionHandler(msgService, orgService)
	avatarHandler := NewAvatarHandler(orgService)
	sessViewHandler := NewSessionViewHandler(sessViewService)
	multiHandler := NewMultiHandler(orgService, msgService)
	mqttHandler := NewMqttHandler(mqttService)
	translateHandler := NewTranslateHandler(translateClient)

	router := &Router{
		r:                r,
		orgHandler:       orgHandler,
		msgHandler:       msgHandler,
		callbackHandler:  callbackHandler,
		sessionHandler:   sessionHandler,
		avatarHandler:    avatarHandler,
		appHandler:       appHandler,
		sessViewHandler:  sessViewHandler,
		multiHandler:     multiHandler,
		authTokenCache:   authTokenCache,
		mqttHandler:      mqttHandler,
		translateHandler: translateHandler,
	}

	//初始化router
	router.openRouter()
	router.userRouter()
	router.tenantRouter()
	router.appRouter()
	router.tenantUserRouter()
}

这段代码是我当时的噩梦,每次一个底层对象加一个参数,链条上的依赖对象都要改动,参与把参数透传到底层对象来。

以致于我不胜其烦,开始搜索 go-spring。我知道这是一条邪路,但我真的太痛了。

后来我的实习师傅听说我在问 go-spring 的事情,过来嘲笑了我一番,然后告诉了我有个工具叫wire,是专门用来做依赖注入的。

为了感谢他帮我脱离苦海,他嘲笑我的事情我就当没发生过,不然刚刚那段代码肯定已经跑在线上了。

image.png

没错。IOC 说完该说 DI了。还记得大学的时候我的老师说过一句话:如果不能理解IOC和DI就认为他们是同一个东西,他们都是Spring。

Spring真的是恐怖如斯,抢占了IOC的名头还不够,连DI都要赶尽杀绝。

说回正题,还是熟悉的配方,依赖注入是什么?引用王争大佬一句话,依赖注入是一个标价25美元,实际上只值5美分的概念。

就像我跟你说我是长方体固体定向移动工程师一样。依赖注入也是这种货色。看这段类代码来对比理解依赖注入:

public class Computer {
    // 可以通过反射注入
    private InputDevice inputDevice;  // 输入设备
    private OutputDevice outputDevice; // 输出设备
    private ControlUnit controlUnit; // 控制单元
    private MemoryUnit memoryUnit; // 存储单元
    private LogicUnit logicUnit; // 运算单元

    // 可以通过构造方法注入
    public Computer(InputDevice inputDevice, OutputDevice outputDevice, ControlUnit controlUnit, MemoryUnit memoryUnit, LogicUnit logicUnit) {
        this.inputDevice = inputDevice;
        this.outputDevice = outputDevice;
        this.controlUnit = controlUnit;
        this.memoryUnit = memoryUnit;
        this.logicUnit = logicUnit;
    }

    // 可以通过set方法注入
    public void setInputDevice(InputDeviceinputDevice) {
        this.inputDevice = inputDevice;
    }

    // ....
}

这段代码中,Computer很明显依赖了5个组成部分。要初始化Computer 就需要这5个部分,如果没有这5个部分,computer实例执行对象功能的时候就会有问题。

说完了依赖那就要说注入,注入使用正方的方式来理解更加简单,上面的代码是注入的。那依赖非注入是什么样的?

public class Computer {
    // 非注入方式,直接在类中进行初始化,不依赖其他部分来填充类属性
    private InputDevice inputDevice = new InputDevice();
    private OutputDevice outputDevice = new OutputDevice();
    private ControlUnit controlUnit = new ControlUnit();
    private MemoryUnit memoryUnit = new MemoryUnit();
    private LogicUnit logicUnit = LogicUnit();
}

就像配电脑,有的人喜欢自己装机,有的人喜欢买装好的一体机。自己装机需要折腾,到时候有零件坏了可以换零件。装好的一体机就是方便,但是坏了就得拿去给商家修了。

如果程序员如果没有一把趁手的键盘用来威慑,那产品就会蹬鼻子上脸(bushi)。所以公司配置完机器之后,很多的程序员都会自己搞一把键盘,再弄个鼠标,甚至显示器都给替换掉。

image.png

现在知道为啥依赖注入实际上只值5美分了吧?因为使用起来实在是太简单了。那Spring和依赖注入有什么关系?死鬼怎么这么快就忘了 @Autowired?

谷歌有个工具叫wire用来做依赖注入,那@Autowired很明显就是用来做自动依赖注入。(这名字真的拿捏了)手动和自动应该怎么选择我想应该是刻在程序员骨子里的。

有一个需求,把文件夹中的文件名全部加个后缀,你愿意花5分钟手动改,还是愿意花10分钟写段代码自动化?这也许就是程序员独有的浪漫吧。

image.png

至于Spring为什么会成为IOC和DI的代名词,我想就是因为它的使用IOC和DI的方式太过简单,连门槛都给磨平了。要用IOC,直接一个注解@Component,要用DI,还是一个注解 @Autowired。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值