我从头到尾实现了一个Golang的依赖注入框架,并且集成了gin、xorm、redis、cron、消息中间件等功能;自己觉得还挺好用的,推荐给你!也欢迎一起维护!
github地址:https://github.com/gone-io/gone
文档地址:https://goner.fun/
如果可能,请帮忙在github上点个 ⭐️ ;万分感谢!!
Gone 支持对Slice
和Map
进行注入,即支持如下写法的:
type BGoner struct {
gone.Flag
aSlice1 []*AGoner `gone:"*"` //被注入的属性为Goner指针Slice
aSlice2 []AGoner `gone:"*"` //被注入的属性为Goner值Slice
aMap1 map[string]*AGoner `gone:"*"` //被注入的属性为Goner指针的map
aMap2 map[string]AGoner `gone:"*"` //被注入的属性为Goner值的map
}
注入的规则如下:
-
- Slice 和 Map 的元素类型可以是 Goner指针类型 和 Goner的值类型,也可以是一个接口类型;
-
- Gone会将所有类型兼容的Goner注入到Slice 和 Map;
-
- Map key的类型只能是string;
-
- Map 键值为被注入Goner的GonerId,埋葬时没有指定GonerId的匿名Goner,Gone会自动生成一个Id。
⚠️不推荐使用值作为Slice和Map的类型
下面是完整的例子:
package main
import (
"fmt"
"github.com/gone-io/gone"
)
type AGoner struct {
gone.Flag //tell the framework that this struct is a Goner
Name string
}
func (g *AGoner) Say() string {
return fmt.Sprintf("I am the AGoner, My name is: %s", g.Name)
}
type BGoner struct {
gone.Flag
aSlice1 []*AGoner `gone:"*"` //被注入的属性为Goner指针Slice
aSlice2 []AGoner `gone:"*"` //被注入的属性为Goner值Slice
aMap1 map[string]*AGoner `gone:"*"` //被注入的属性为Goner指针的map
aMap2 map[string]AGoner `gone:"*"` //被注入的属性为Goner值的map
}
// AfterRevive executed After the Goner is revived; After `gone.Run`, gone framework detects the AfterRevive function on goners and runs it.
func (g *BGoner) AfterRevive() gone.AfterReviveError {
for _, a := range g.aSlice1 {
fmt.Printf("aSlice1:%s\n", a.Say())
}
println("")
for _, a := range g.aSlice2 {
fmt.Printf("aSlice2:%s\n", a.Say())
}
println("")
for k, a := range g.aMap1 {
fmt.Printf("aMap1[%s]:%s\n", k, a.Say())
}
println("")
for k, a := range g.aMap2 {
fmt.Printf("aMap2[%s]:%s\n", k, a.Say())
}
return nil
}
// 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"
}
func main() {
gone.Run(func(cemetery gone.Cemetery) error {
cemetery.
Bury(NewA1()).
Bury(&AGoner{Name: "Anonymous"}).
Bury(NewA2()).
Bury(&BGoner{})
return nil
})
}
例子执行的结果如下:
求赞助
如果觉得还可以,请帮忙在github上点个 ⭐️吧:
github地址:https://github.com/gone-io/gone
福利:🔥添加交流群,赠送 Golang 多套 学习资料,夯实基础👍🏻👍🏻
上一篇:Gone框架介绍6 - 如何使用gone开发web服务
下一篇:Gone框架介绍8 - gone支持的注入方式总结