在独立的Java应用程序中使用Spring 3 autowire [英] Using Spring 3 autowire in a standalone Java application

查看:81
本文介绍了在独立的Java应用程序中使用Spring 3 autowire的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

public class Main {

    public static void main(String[] args) {
        Main p = new Main();
        p.start(args);
    }

    @Autowired
    private MyBean myBean;
    private void start(String[] args) {
        ApplicationContext context = 
            new ClassPathXmlApplicationContext("META-INF/config.xml");
        System.out.println("my beans method: " + myBean.getStr());
    }
}

@Service 
public class MyBean {
    public String getStr() {
        return "string";
    }
}







<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
    <context:annotation-config /> 
    <context:component-scan base-package="mypackage"/>
</beans>

为什么这不工作?我得到 NullPointerException 。可以在独立应用程序中使用自动装配?

Why doesn't this work? I get NullPointerException. Is it possible to use autowiring in a standalone application?

推荐答案

Spring可在独立应用程序中工作。你使用错误的方式来创建一个spring bean。正确的方法是这样做:

Spring works in standalone application. You are using the wrong way to create a spring bean. The correct way to do it like this:

@Component
public class Main {

    public static void main(String[] args) {
        ApplicationContext context = 
            new ClassPathXmlApplicationContext("META-INF/config.xml");

        Main p = context.getBean(Main.class);
        p.start(args);
    }

    @Autowired
    private MyBean myBean;
    private void start(String[] args) {
        System.out.println("my beans method: " + myBean.getStr());
    }
}

@Service 
public class MyBean {
    public String getStr() {
        return "string";
    }
}

在第一种情况(问题中的一个)您正在自己创建对象,而不是从Spring上下文获取对象。所以Spring不会有机会 Autowire 依赖关系(导致 NullPointerException )。

In the first case (the one in the question), you are creating the object by yourself, rather than getting it from the Spring context. So Spring does not get a chance to Autowire the dependencies (which causes the NullPointerException).

在第二种情况(这个答案中的一个)中,你从Spring的上下文中获取了bean,因此它是Spring管理的,Spring负责自动连线

In the second case (the one in this answer), you get the bean from the Spring context and hence it is Spring managed and Spring takes care of autowiring.

这篇关于在独立的Java应用程序中使用Spring 3 autowire的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆