在独立的 Java 应用程序中使用 Spring 3 自动装配 [英] Using Spring 3 autowire in a standalone Java application
问题描述
这是我的代码:
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 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 负责 autowiring
.
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 自动装配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!