爲什麼在使用@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());
}
}
謝謝。
可以在非測試環境中使用'@ Autowired'來完成。請給你更多的背景。 –
這取決於你正在嘗試做什麼。請展示一些更多的代碼,讓大家清楚地看到你正在嘗試做什麼 – geoand