bean

package
v1.15.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2024 License: Apache-2.0 Imports: 5 Imported by: 0

README

自动注入

demo


package main

import (
	"fmt"
	"github.com/eolinker/apinto-standard/common/bean"
)

type AutowiredTester interface {
	Name()string
}
type AutowiredTester1 struct {

}

func (a *AutowiredTester1) Name() string {
	return "AutowiredTester1"
}
var(
  tester AutowiredTester
)
func init() {
	// 依赖注入,这里必须用指针
	bean.Autowired(&tester)
}
func main() {

	var t1 AutowiredTester = new(AutowiredTester1)

	// 注入 AutowiredTester, 这里必须用指针
	bean.Injection(&t1)

	bean.Check()// 检查是否完成了完整注入

	fmt.Println(tester.Name())
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	//Default 默认的bean
	Default = NewContainer()
)

Functions

func AddInitializingBean

func AddInitializingBean(handler InitializingBeanHandler)

AddInitializingBean 注册完成回调接口, 执行check成功后会调用回调接口

func AddInitializingBeanFunc

func AddInitializingBeanFunc(handler func())

AddInitializingBeanFunc 注册完成回调方法, 执行check成功后会调用回调方法

func Autowired

func Autowired(is ...interface{})

AutowiredManager 声明需要注入的接口变量 如果目标接口还没有注入实例,会在注入后给将接口实例赋值给指针 如果目标接口类型已经被注入,会立刻获得有效的接口实例

Example
package main

import (
	"log"
)

type NameInterface interface {
	DO()
}
type TestImpl struct {
	name string
}

func (t *TestImpl) DO() {
	log.Println("do by:", t.name)
}

func init() {

	var nameInterface NameInterface
	// 这里一定要要用指针
	Autowired(&nameInterface)

	AddInitializingBeanFunc(func() {
		log.Println("auto wired done")
		nameInterface.DO()
	})

}

func main() {

	t := &TestImpl{name: "demo bean"}
	// 转换成注入目标的类型
	var i NameInterface = t
	// 这里也要用指针,否则反射识别类型会出问题
	Injection(&i)
	// 检查是否有缺失
	err := Check()
	if err != nil {
		panic(err)
	}
}
Output:

func Check

func Check() error

Check 对默认的bean容器执行检查, 如果所有Autowired需求都被满足,返回nil,否则返回与缺失实例有关都error

func GetByName

func GetByName(namespace string) (interface{}, bool)

func GetListByName

func GetListByName(namespaces ...string) []interface{}

func Injection

func Injection(i interface{})

Injection 注入一个构造好的实例

如果注入多个相同接口类型,后注入的实例会覆盖先注入的实例

func InjectionDefault

func InjectionDefault(i interface{})

InjectionDefault 注入一个构造好的默认实例 * 如果注入多个相同接口类型,后注入的实例会覆盖先注入的实例,default实例不会覆盖普通实例

func RegisterByName

func RegisterByName(namespace string, m interface{})

Types

type Container

type Container interface {
	Autowired(p interface{})
	Injection(i interface{})
	InjectionDefault(i interface{})
	Check() error
	AddInitializingBean(handler InitializingBeanHandler)
	AddInitializingBeanFunc(handler func())
}

Container bean 容器接口

func NewContainer

func NewContainer() Container

NewContainer 创建新的 bean 容器

type InitializingBeanHandler

type InitializingBeanHandler interface {
	AfterPropertiesSet()
}

InitializingBeanHandler 注入完成后的回调

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL