Gone框架介绍7 - Slice注入和 Map注入

我从头到尾实现了一个Golang的依赖注入框架,并且集成了gin、xorm、redis、cron、消息中间件等功能;自己觉得还挺好用的,推荐给你!也欢迎一起维护!
github地址:https://github.com/gone-io/gone
文档地址:https://goner.fun/
如果可能,请帮忙在github上点个 ⭐️ ;万分感谢!!

Gone 支持对SliceMap进行注入,即支持如下写法的:

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
}

注入的规则如下:

    1. Slice 和 Map 的元素类型可以是 Goner指针类型 和 Goner的值类型,也可以是一个接口类型;
    1. Gone会将所有类型兼容的Goner注入到Slice 和 Map;
    1. Map key的类型只能是string;
    1. 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支持的注入方式总结

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dapeng-大鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值