2017-06-04 175 views
1

我是Spring和Maven的新手。我正在尝试使用maven原型构建一个spring应用程序。所以我已经用maven pom.xml设置了这个项目。所有的东西都可以正常工作,但唯一的问题是我的IDE(netbeans)不包括我的spring.xml在classpath中。因此,构建失败,文件未找到异常。我必须专门给出spring.xml的完全限定路径才能使其工作。所以下面如何在Maven Classpath中添加资源

失败 - AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

如果我改变它下面它的工作原理 -

AbstractApplicationContext context = new ClassPathXmlApplicationContext("file:///Users/shoukat/NetBeansProjects/csm/src/main/java/spring.xml"); 

我发现,这种情况正在发生,因为我的类路径中不包括主/ java目录。下面是结果,当我尝试使用下面的代码 - 打印的类加载器的URL

 ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader(); 

     //Get the URLs 
     URL[] urls = ((URLClassLoader)sysClassLoader).getURLs(); 

     for(int i=0; i< urls.length; i++) 
     { 
      System.out.println(urls[i].getFile()); 
     } 

结果 -

/Users/shoukat/NetBeansProjects/csm/target/classes/ 
/Users/shoukat/.m2/repository/commons-logging/commons-logging/1.1.3/commons-logging-1.1.3.jar 
/Users/shoukat/.m2/repository/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar 
/Users/shoukat/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.5/jcl-over-slf4j-1.7.5.jar 
/Users/shoukat/.m2/repository/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar 
/Users/shoukat/.m2/repository/org/springframework/spring-context/4.0.0.RELEASE/spring-context-4.0.0.RELEASE.jar 
/Users/shoukat/.m2/repository/org/springframework/spring-aop/4.0.0.RELEASE/spring-aop-4.0.0.RELEASE.jar 
/Users/shoukat/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar 
/Users/shoukat/.m2/repository/org/springframework/spring-beans/4.0.0.RELEASE/spring-beans-4.0.0.RELEASE.jar 
/Users/shoukat/.m2/repository/org/springframework/spring-core/4.0.0.RELEASE/spring-core-4.0.0.RELEASE.jar 

理想情况下这应该也包括src目录,因为我把我的资源春那里有.xml文件。我需要更改什么,以便我的src/main目录包含在classpath中,而且我不必使用我的spring.xml文件的完全限定系统路径对我的程序进行硬编码?

感谢

回答

2

当你的classpath但行家使用ClassPathXmlApplicationContext搜索spring.xml当编译忽略像* .XML放在src/main/java

对于这种资源的工作,你必须创建资源文件夹,该文件夹树是这样的:

src/main/java/.. 
src/main/resources/spring.xml 

然后你可以使用:

AbstractApplicationContext context = new ClassPathXmlApplicationContext(“spring.xml”);

Maven - Introduction to the Standard Directory Layout