Skip to content

Commit 4a3b79a

Browse files
committed
When the refresh fails, the injected beans will be destroyed
1 parent 259c5e4 commit 4a3b79a

File tree

2 files changed

+75
-1
lines changed

2 files changed

+75
-1
lines changed

gs/gs.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,8 @@ func (c *container) Refresh() (err error) {
453453
stack := newWiringStack(c.logger)
454454

455455
defer func() {
456+
c.dependencies = stack.dependencies
457+
456458
if err != nil || len(stack.beans) > 0 {
457459
if nil != err {
458460
err = fmt.Errorf("container refresh failed\n%s\n↳%w", stack.path(), err)
@@ -481,7 +483,6 @@ func (c *container) Refresh() (err error) {
481483
}
482484
}
483485

484-
c.dependencies = stack.dependencies
485486
c.state = Refreshed
486487

487488
cost := time.Now().Sub(start)

gs/gs_test.go

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3126,3 +3126,76 @@ func TestContextGetWire(t *testing.T) {
31263126
})
31273127

31283128
}
3129+
3130+
type beanA struct {
3131+
markInit bool
3132+
markDestroy bool
3133+
}
3134+
3135+
func (b *beanA) OnInit(ctx context.Context) error {
3136+
b.markInit = true
3137+
return nil
3138+
}
3139+
3140+
func (b *beanA) OnDestroy() {
3141+
b.markDestroy = true
3142+
}
3143+
3144+
type beanB struct {
3145+
BeanA *beanA `autowire:""`
3146+
markInit bool
3147+
markDestroy bool
3148+
}
3149+
3150+
func (b *beanB) OnInit(ctx context.Context) error {
3151+
return errors.New("init failed")
3152+
}
3153+
3154+
func (b *beanB) OnDestroy() {
3155+
b.markDestroy = true
3156+
}
3157+
3158+
type beanC struct {
3159+
BeanB *beanB `autowire:""`
3160+
markInit bool
3161+
markDestroy bool
3162+
}
3163+
3164+
func (b *beanC) OnInit(ctx context.Context) error {
3165+
b.markInit = true
3166+
return nil
3167+
}
3168+
3169+
func (b *beanC) OnDestroy() {
3170+
b.markDestroy = true
3171+
}
3172+
3173+
func TestBeanDestroy(t *testing.T) {
3174+
3175+
c := New()
3176+
ba := c.Object(new(beanA)).Interface().(*beanA)
3177+
bb := c.Object(new(beanB)).Interface().(*beanB)
3178+
bc := c.Object(new(beanC)).Interface().(*beanC)
3179+
3180+
err := c.Refresh()
3181+
assert.NotNil(t, err)
3182+
3183+
assert.Equal(t, ba.markInit, true)
3184+
assert.Equal(t, bb.markInit, false)
3185+
assert.Equal(t, bc.markInit, false)
3186+
3187+
assert.Equal(t, ba.markDestroy, false)
3188+
assert.Equal(t, bb.markDestroy, false)
3189+
assert.Equal(t, bc.markDestroy, false)
3190+
3191+
c.Close()
3192+
3193+
assert.Equal(t, ba.markInit, true)
3194+
assert.Equal(t, bb.markInit, false)
3195+
assert.Equal(t, bc.markInit, false)
3196+
3197+
assert.Equal(t, ba.markDestroy, true)
3198+
assert.Equal(t, bb.markDestroy, false)
3199+
assert.Equal(t, bc.markDestroy, false)
3200+
3201+
}

0 commit comments

Comments
 (0)