简体   繁体   中英

Spring test/production application context

Why when running spring tests with @ContextConfiguration(...) @Autowired works automatically and when running Java application I get NullPointerException?

With following example I get 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();
    }
}

With following example it works:

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();
    }
}

In tests no need of doing context.getBean(), it just works with @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());
    }
}

Thanks.

Anytime you use @Autowired , the class into which the dependency is going to be injected needs to be managed by Spring.

A test with:

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

is managed by Spring. When the annotations do not exist, the class is not managed by Spring and therefor no dependency injection is performed

You're expecting Spring to be able to inject beans into an instance it doesn't manage.

You're creating your object manually

FinalTest finalTest = new FinalTest();

Spring can only inject beans into objects it manages. Here, Spring has nothing to do with the object created above.

Declare a FinalTest bean in your context and retrieve it. It will have been autowired if your configuration is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM