PostConstruct added

This commit is contained in:
crusader 2018-09-04 15:44:42 +09:00
parent 93072d1a5e
commit d72db42216
4 changed files with 43 additions and 3 deletions

2
Gopkg.lock generated
View File

@ -5,7 +5,7 @@
branch = "master"
name = "git.loafle.net/overflow/annotation-go"
packages = ["."]
revision = "178b12d303bdd83566a35d71cce68b0c6cc1f4d3"
revision = "b94873cf6c40c8a46393f4e9f229eee152e2eb1b"
[[projects]]
branch = "master"

View File

@ -0,0 +1,19 @@
package annotation
// @Inject(name? string)
import (
"reflect"
oa "git.loafle.net/overflow/annotation-go"
)
func init() {
oa.Register(PostConstructAnnotationType)
}
var PostConstructAnnotationType = reflect.TypeOf((*PostConstructAnnotation)(nil))
type PostConstructAnnotation struct {
oa.Annotation `@name:"@PostConstruct"`
}

View File

@ -170,6 +170,7 @@ func (r *InstanceRegistry) GetInstance(t reflect.Type) (instance interface{}, er
td *TypeDefinition
injectableV interface{}
ok bool
name string
)
rt, _, _ := our.GetTypeInfo(t)
@ -192,7 +193,8 @@ func (r *InstanceRegistry) GetInstance(t reflect.Type) (instance interface{}, er
if a, err := oa.GetTypeAnnotation(td.Type, annotation.InjectableAnnotationType); nil == err && nil != a {
_a := a.(*annotation.InjectableAnnotation)
if "" != _a.Name {
r.instanceByName[_a.Name] = instance
name = _a.Name
r.instanceByName[name] = instance
}
}
@ -200,8 +202,13 @@ func (r *InstanceRegistry) GetInstance(t reflect.Type) (instance interface{}, er
defer func() {
if nil != err {
instance = nil
if _, ok := r.instanceByType[td.RealType]; ok {
delete(r.instanceByType, td.RealType)
}
if _, ok := r.instanceByName[name]; ok {
delete(r.instanceByName, name)
}
}
}()
var (
@ -273,6 +280,13 @@ func (r *InstanceRegistry) GetInstance(t reflect.Type) (instance interface{}, er
}
}
if as, err := oa.GetMethodAnnotationsByType(td.Type, annotation.PostConstructAnnotationType); nil == err && nil != as {
for k := range as {
ins := make([]reflect.Value, 0)
reflect.ValueOf(instance).MethodByName(k).Call(ins)
}
}
return
}

View File

@ -1,6 +1,7 @@
package di
import (
"log"
"reflect"
"testing"
@ -21,9 +22,15 @@ var InjectServiceType = reflect.TypeOf((*InjectService)(nil))
type InjectService struct {
Service *InjectableService `annotation:"@Inject('name': 'InjectableService')"`
_Init oa.MethodAnnotation `annotation:"@PostConstruct()"`
R string
}
func (s *InjectService) Init() {
log.Print("Init")
}
func TestNew(t *testing.T) {
type args struct {
parent Registry