2014-04-26 21 views
0

爲什麼在使用@ContextConfiguration(...)@Autowired運行spring測試時會自動運行,並且在運行Java應用程序時會出現NullPointerException?春季測試/生產應用上下文

有了下面的例子中,我得到NullPointerException異常:

public class FinalTest { 

    @Autowired 
    private App app; 

    public FinalTest() { 
    } 

    public App getApp() { 
     return app; 
    } 

    public void setApp(App app) { 
     this.app = app; 
    } 

    public static void main(String[] args) { 

     ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 

     FinalTest finalTest = new FinalTest(); 
     finalTest.getApp().getCar().print(); 
     finalTest.getApp().getCar().getWheel().print(); 
    } 
} 

有了下面的例子中它的工作原理:

public class FinalTest { 

    private App app; 

    public FinalTest() { 
    } 

    public App getApp() { 
     return app; 
    } 

    public void setApp(App app) { 
     this.app = app; 
    } 

    public static void main(String[] args) { 

     ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 

     FinalTest finalTest = new FinalTest(); 
     finalTest.setApp((App)context.getBean("app")); 
     finalTest.getApp().getCar().print(); 
     finalTest.getApp().getCar().getWheel().print(); 
    } 
} 

在測試中沒有必要做context.getBean()的,它只是與@Autowired工作:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={"/applicationContext-test.xml"}) 
public class AppTest{ 

    @Autowired 
    private App app; 

    @Test 
    public void test(){ 

     assertEquals("This is a SEAT_test car.", this.app.getCar().toString()); 
     assertEquals("This is a 10_test wheel.", this.app.getCar().getWheel().toString()); 
    } 
} 

謝謝。

+0

可以在非測試環境中使用'@ Autowired'來完成。請給你更多的背景。 –

+0

這取決於你正在嘗試做什麼。請展示一些更多的代碼,讓大家清楚地看到你正在嘗試做什麼 – geoand

回答

2

無論何時使用@Autowired,依賴將要注入的類都需要由Spring進行管理。

與測試:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={"/applicationContext-test.xml"}) 

由Spring管理。當註釋不存在時,該類不受Spring管理,因此沒有 執行依賴注入

+0

好吧,現在我明白了由Spring管理的測試的重點。非常感謝! – David

+0

@大衛沒問題! – geoand

0

你在期待Spring能夠將bean注入到它不管理的實例中。

你創建你的對象手動

FinalTest finalTest = new FinalTest(); 

春天只能注入豆成它所管理的對象。在這裏,Spring與上面創建的對象無關。

在您的上下文中聲明FinalTest bean並檢索它。如果您的配置正確,它將會自動裝配。

+0

好吧,我明白,但爲什麼在測試中可能呢?是否因爲測試是由Spring管理的對象? – David

+0

@David這與測試無關。它與你的配置有關。在你的測試中,Spring爲你的測試類創建一個bean。由於它管理這個bean,它可以自動裝載'App' bean。如果你聲明瞭一個類型爲「FinalTest」的bean,它也可以做同樣的事情。 –

+0

我現在完全明白了。非常感謝您的解釋! – David