我从头到尾实现了一个Golang的依赖注入框架,并且集成了gin、xorm、redis、cron、消息中间件等功能;自己觉得还挺好用的,推荐给你!也欢迎一起维护!
github地址:https://github.com/gone-io/gone
文档地址:https://goner.fun/
如果可能,请帮忙在github上点个 ⭐️ ;万分感谢!!
在前面的篇章中,我们所有的例子实际上都是按类型的匿名注入;匿名注入时,如果存在多个同类型的Goner,被注入只会是其中一个,通常是最先被复活的那个。在Gone中,是支持按名字注入的(也就是具名注入)。
首先,Cemetery.Bury
函数的完整定义是这样的 Bury(Goner, ...GonerId) Cemetery
,这样的定义有两层考虑:
-
- 用于支持具名埋葬,第二个参数是可选的,允许传入一个字符串作为Goner的ID(GonerId);
-
- 使Bury函数支持链式调用。
实现具名埋葬,我们的代码可以这样写:
// Priest Responsible for putting Goners that need to be used into the framework
func Priest(cemetery gone.Cemetery) error {
cemetery.
Bury(&AGoner{Name: "Injected Goner1"}, "A1"). //埋葬第一个AGoner,ID=A1
Bury(&AGoner{Name: "Injected Goner2"}, "A2"). //埋葬第二个AGoner,ID=A2
Bury(&BGoner{})
return nil
}
另外也可以这样写,这样写的好处是将Goner的构造和埋葬进行解耦:
// NewA1 构造A1 AGoner
func NewA1() (gone.Goner, gone.GonerId) {
return &AGoner{Name: "Injected Goner1"}, "A1"
}
// NewA2 构造A2 AGoner
func NewA2() (gone.Goner, gone.GonerId) {
return &AGoner{Name: "Injected Goner2"}, "A2"
}
// Priest Responsible for putting Goners that need to be used into the framework
func Priest(cemetery gone.Cemetery) error {
cemetery.
Bury(NewA1()).
Bury(NewA2()).
Bury(&BGoner{})
return nil
}
然后,就是结构体的具名注入,举个例子就能立刻明白:
type BGoner struct {
gone.Flag //tell the framework that this struct is a Goner
a *AGoner `gone:"*"` //匿名注入一个AGoner
a1 *AGoner `gone:"A1"` //具名注入A1
a2 *AGoner `gone:"A2"` //具名注入A2
}
注意:上面代码,结构体属性后的标签:
gone:"*"
是按类型的匿名注入;gone:"A1"
是注入ID=A1
的AGoner的具名注入。
就是说,gone
标签的值如果是*
就是匿名注入;如果不是*
,标签值就是要注入Goner的名字,也就是具名注入;当然,因为go是强类型的,所以无论 匿名注入 还是 具名注入 的 Goner 都必须是类型兼容的,否则注入失败。
求赞助
如果觉得还可以,请帮忙在github上点个 ⭐️吧:
github地址:https://github.com/gone-io/gone
福利:🔥添加交流群,赠送 Golang 多套 学习资料,夯实基础👍🏻👍🏻
上一篇: Gone框架介绍3 - 使用gone命令,自动生成Priest函数
下一篇: Gone框架介绍5 - 匿名注入与具名注入