【发布时间】:2013-12-26 12:52:11
【问题描述】:
有没有办法直接从 main 方法运行注解配置的 Spring 应用程序? 我仍然在下面得到 NullPointerException 运行代码。请注意,我没有使用 SpringMVC,并且当我使用在 context.xml 中定义的 bean,通过 context.getBean 方法注入 main 方法时,所有代码都可以正常工作(没有错误)-但我只是想知道这是否是一种方法仅使用注释管理运行它?
//IElem.java
package com.pack.elem;
public interface IElem {
public abstract String sayHello();
}
//Elem.java
package com.pack.elem;
import org.springframework.stereotype.Component;
@Component
public class Elem implements IElem{
@Override
public String sayHello() {
return ("Hello from Elem class object");
}
}
//RunElem.java
package com.pack.elem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RunElem {
@Autowired
private IElem elem;
public void runHello(){
System.out.println(elem.sayHello());
}
}
//Main.java
package com.pack.main;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.pack.elem.RunElem;
public class Main {
@Autowired
private RunElem runelem;
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("/META-INF/application-context.xml");
new Main().runRun();
}
private void runRun(){
runelem.runHello();
}
}
<!--/META-INF/application-context.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.pack"/>
</beans>
【问题讨论】:
-
因此您希望在 spring 范围之外创建的实例由 Spring 自动管理。您不应该自己构建实例,而应该使用 spring 已经配置的实例。换句话说,从
ApplicationContext中检索它,而不是自己构建。 -
@RakeshGoyal 你说得对。这是相似的。我以前没有发现这个。也许会有所帮助。谢谢。
-
@M.Deinum 现在我很清楚了。谢谢!