2015-07-03 68 views
1

我想在StaticApplicationContext中自動裝入一個bean,但雖然我可以插入一個bean併成功檢索它,但我無法在另一個bean中自動裝入它。下面是一個簡單的例子來解釋我的意思。StaticApplicationContext中的autowire bean

在此示例中,第一個斷言成功,第二個斷言失敗。請注意,如果我註釋掉此方法的行,而取消註釋使用AnnotationConfigApplicationContext的方法#2的行,自動裝配將起作用。不過,我想使用StaticApplicationContext方法進行這項工作。

@Test 
public void testAutowire() { 

    //context configuration approach #1 
    StaticApplicationContext context = new StaticApplicationContext(); 
    context.registerSingleton("child", Child.class); 

    //context configuration approach #2 
    //AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Child.class); 

    Parent parent = new Parent(); 

    context.getAutowireCapableBeanFactory().autowireBean(parent); 

    //this is successful 
    Assert.notNull(context.getBean(Child.class), "no bean found"); 
    //this works only with AnnotationConfigApplicationContext and not with StaticApplicationContext 
    Assert.notNull(parent.child, "no child autowired"); 
} 

public static class Parent { 

    @Autowired 
    Child child; 

    public Parent() { 

    } 
} 

public static class Child { 

    public Child() { 
    } 
} 

問題出在哪裏?

+0

嘗試與上下文太註冊父。 –

+0

我試過了,它不能用於註冊父項。事實上,我認爲這樣做並不合理,因爲我在上下文之外手動創建父對象。這就是我需要使用autowireBean方法執行自動裝配的原因 – Marios

回答

7

AnnotationConfigApplicationContext內部註冊AutowiredAnnotationBeanPostProcessor bean以處理@Autowired註釋。 StaticApplicationContext沒有。

您可以自己

context.registerSingleton("someName", AutowiredAnnotationBeanPostProcessor.class); 

增加,但那麼你需要refreshApplicationContext

context.refresh(); 
相關問題