Java Spring测试/生产应用程序上下文

Java Spring测试/生产应用程序上下文,java,spring,Java,Spring,为什么在运行带有@ContextConfiguration(…)@Autowired的spring测试时会自动工作,而在运行Java应用程序时会出现NullPointerException 通过以下示例,我得到NullPointerException: public class FinalTest { @Autowired private App app; public FinalTest() { } public App getApp() {

为什么在运行带有@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());
    }
}

谢谢。

您希望Spring能够将bean注入到它无法管理的实例中

您正在手动创建对象

FinalTest finalTest = new FinalTest();
Spring只能将bean注入到它管理的对象中。这里,Spring与上面创建的对象无关


在上下文中声明一个
FinalTest
bean并检索它。如果您的配置正确,它将被自动连接。

无论何时使用
@autowired
,依赖项将被注入的类都需要由Spring管理

具有以下特性的测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext-test.xml"})
由Spring管理。当注释不存在时,该类不由Spring管理,因此不存在
依赖项注入是执行的

您可以在非测试环境中使用
@Autowired
执行。请给你正在做的事情提供更多的背景。这取决于你想做什么。请展示更多的代码,以便每个人都能清楚地了解你想做什么,我理解这一点,但为什么在测试中这是可能的呢?是因为测试是由Spring管理的对象吗?@David这与测试无关。这与您的配置有关。在您的测试中,Spring为您的测试类创建了一个bean。因为它管理这个bean,所以它可以自动连接
App
bean。如果您声明了一个类型为
FinalTest
的bean,它也可以这样做。我现在完全理解了。谢谢你的解释!好了,现在我理解了Spring管理的测试的要点。谢谢!