之前在写 java 用 Spring 的时候,最爽的莫不过于依赖注入了.现在写 golang,常常苦于没有这样一个库,模仿 Spring 的方式写了一个简单的依赖注入库.能显著改进代码编排结构.降低耦合.
围观地址 https://github.com/xcrossed/let-go-inject
项目采用 go mod 方式管理依赖.当然作为库,没有任何依赖,
使用方式
package mainimport ("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:%v", 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:%v", dao == biz.Dao)fmt.Printf("equals:%v", biz == ctl.Biz)}http://p1.pstatp.com/list/dfic-imagehandler/955f9874-3759-4fab-bdee-064cff9174ca
欢迎围观吐槽