go依赖注入_从0开始实现 go 依赖注入库

38d2d1a95828d70cdb57a496ec85dd39.png

之前在写 java 用 Spring 的时候,最爽的莫不过于依赖注入了.现在写 golang,常常苦于没有这样一个库,模仿 Spring 的方式写了一个简单的依赖注入库.能显著改进代码编排结构.降低耦合.

围观地址 https://github.com/xcrossed/let-go-inject

项目采用 go mod 方式管理依赖.当然作为库,没有任何依赖,

使用方式

package main
import (
	"fmt"
	"github.com/xcrossed/let-go-inject/inject"
)
type Dao struct {
	Name string
}
type BizInterface interface {
	SayHello(string)
}
type biz struct {
	Dao *Dao `inject:""` 
}
func (biz *biz) SayHello(name string) {
	fmt.Printf("say:%vn", name)
}
type Controll struct {
	Biz BizInterface `inject:"biz.impl"` 
}
func main() {
	beanfactory := inject.NewDefaultBeanFactory()
	dao := &Dao{"my name is dao."}
	beanfactory.RegisterBean(dao)
	biz := &biz{}
	beanfactory.RegisterBeanWithName("biz.impl", biz)
	ctl := &Controll{}
	beanfactory.RegisterBean(ctl)
	beanfactory.AutoWire()
	fmt.Println(biz.Dao == nil)
	fmt.Println(ctl.Biz == nil)
	fmt.Printf("equals:%vn", dao == biz.Dao)
	fmt.Printf("equals:%vn", biz == ctl.Biz)
}

欢迎围观吐槽

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值