有沒有辦法運行Spring應用程序配置註釋,直接從主要方法? 我仍然得到下面的運行代碼的NullPointerException。請注意,我沒有使用SpringMVC,當我使用在context.xml中定義的bean,通過context.getBean方法注入到main方法內部時,所有代碼都很完美(沒有錯誤) - 但我只是想知道它是否是一種方法管理運行這隻與註釋?春天 - NullPointerException當自動裝配
//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配置的實例。換句話說,從'ApplicationContext'中檢索它,而不是構建自己的。 –
@RakeshGoyal你有權利。它是相似的。我以前沒有找到。也許這會有所幫助。謝謝。 – kropla
@ M.Deinum現在對我來說很清楚。謝謝! – kropla