我在使用最简单的maven-spring应用程序时遇到了一些困难。实际上,BeanFactory
找不到appContext.xml
文件,尽管它位于资源目录中并正确复制到目标目录中。这是我的主要类,dir结构和错误:
// MAIN CLASS
package sas.test.spring;
import java.io.FileInputStream;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
/**
* Hello world!
*/
public class App {
public static void main(String[] args) throws Exception {
System.out.println("Hello World!");
BeanFactory fact = new XmlBeanFactory((Resource) new FileInputStream("appContext.xml"));
GreetingService gs = (GreetingService) fact.getBean("greetingService");
gs.sayGreeting();
}
}
mvn compile
之后的目录结构:
testspring002
|--src
| `--main
| |--java
| | `--sas
| | `--test
| | `--spring
| | |--App.java
| | |--GreetingService.java
| | `--GreetingServiceImpl.java
| `--resources
| `--appContext.xml
...
`--target
`--classes
|--appContext.xml
`--sas
`--test
`--spring
|--App.class
|--GreetingService.class
`--GreetingServiceImpl.class
这是错误:
/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home/bin/java -Dclassworlds.conf=/usr/share/java/maven-2.2.0/bin/m2.conf -Dmaven.home=/usr/share/java/maven-2.2.0 -Dfile.encoding=MacRoman -classpath /usr/share/java/maven-2.2.0/boot/classworlds-1.1.jar org.codehaus.classworlds.Launcher --no-plugin-registry --fail-fast --no-plugin-updates --strict-checksums --update-snapshots -f /Users/sas/Development/workspace_idea/testspring002/pom.xml org.codehaus.mojo:exec-maven-plugin:1.1.1:java
+ Enabling strict checksum verification on all artifact downloads.
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building testspring002
[INFO] task-segment: [org.codehaus.mojo:exec-maven-plugin:1.1.1:java]
[INFO] ------------------------------------------------------------------------
[INFO] Preparing exec:java
[INFO] artifact org.codehaus.mojo:exec-maven-plugin: checking for updates from central
[INFO] No goals needed for project - skipping
[INFO] [exec:java {execution: default-cli}]
Hello World!
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] An exception occured while executing the Java class. null
appContext.xml (No such file or directory)
有什么建议吗?
答案 0 :(得分:4)
谢谢,这个提示做到了。没意识到FileInputStream可能是个问题。但是,我现在使用ApplicationContext并且它可以工作:
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"appContext.xml"});
谢谢&干杯
答案 1 :(得分:2)
是的,因为应用程序上下文XML在/ classes中,这意味着它位于CLASSPATH中。我建议从类加载器调用getResourceAsStream()来获取InputStream而不是FileInputStream。