-
Notifications
You must be signed in to change notification settings - Fork 0
/
BeanFactory.go
104 lines (85 loc) · 2.33 KB
/
BeanFactory.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package ioc
import (
"reflect"
)
var BeanFactory *BeanFactoryImpl
func init() {
BeanFactory = NewBeanFactory()
}
type BeanFactoryImpl struct {
beanMapper BeanMapper
}
func NewBeanFactory() *BeanFactoryImpl {
return &BeanFactoryImpl{beanMapper: make(BeanMapper)}
}
func (this *BeanFactoryImpl) GetBeanMapper() BeanMapper {
return this.beanMapper
}
// 向beanMapper添加内容
func (this *BeanFactoryImpl) Set(vList ...interface{}) {
if vList == nil || len(vList) == 0 {
return
}
for _, v := range vList {
this.beanMapper.add(v)
}
}
// 从beanMapper获取内容
func (this *BeanFactoryImpl) Get(bean interface{}) interface{} {
if bean == nil {
return nil
}
v := this.beanMapper.get(bean)
if v.IsValid() {
return v.Interface()
}
return nil
}
// 注入依赖
// 参数bean需要传入一个指针,指针指向的内容是结构体
func (this *BeanFactoryImpl) Apply(bean interface{}) {
if bean == nil {
return //如果bean是空则直接返回
}
//获取bean的值
v := reflect.ValueOf(bean)
if v.Kind() == reflect.Ptr {
v = v.Elem() //获取指针指向的内容
}
if v.Kind() != reflect.Struct {
return //如果指针指向的内容不是结构体则返回
}
//遍历结构体成员
for i := 0; i < v.NumField(); i++ {
field := v.Type().Field(i) //得到成员
if v.Field(i).CanSet() && field.Tag.Get("inject") != "" {
if get_v := this.Get(field.Type); get_v != nil { //从beanMapper中取出对应的值
v.Field(i).Set(reflect.ValueOf(get_v)) //给结构体成员设置从ioc容器中取出的值
this.Apply(get_v) //递归调用,因为可能会出现嵌套依赖的情况
}
}
}
}
// 向ioc容器中添加依赖
func (this *BeanFactoryImpl) Config(cfgs ...interface{}) {
for _, cfg := range cfgs {
t := reflect.TypeOf(cfg)
if t.Kind() != reflect.Ptr {
panic("required ptr object") //必须是指针对象
}
if t.Elem().Kind() != reflect.Struct {
continue
}
this.Set(cfg) //把config本身也加入bean
this.Apply(cfg) //处理依赖注入 (new)
v := reflect.ValueOf(cfg)
//遍历所有的类方法
for i := 0; i < t.NumMethod(); i++ {
method := v.Method(i)
callRet := method.Call(nil) //执行类方法
if callRet != nil && len(callRet) == 1 {
this.Set(callRet[0].Interface()) //将类方法的执行结果塞入到ioc容器中
}
}
}
}