@ContextConfiguration (...) @Autowired가 자동으로 작동하고 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();
}
}
다음 예제와 함께 작동 :
context.getBean()를 수행의 필요, 그냥 @Autowired와 함께 작동하지 테스트에서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();
}
}
:
@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