日期:2014-05-20  浏览次数:20725 次

【求助】想把spring配置放在jar包外,main方法里该怎么读取写”
如题 main方法里该怎么写才能读取到放在jar包外面的applicationContext.xml呢?


上图是文件夹内jar包的分布,fileWatcher_lib是项目中运用到的外部包,fileWatcher.jar是自己写的里面Main类是主方法 下图是main方法的开头读取配置文件,试过几个方法 (1)ApplicationContext ac = new ClassPathXmlApplicationContext("C:\Users\q30084th\Desktop\PCtest\applicationContex t.xml");
(2)写一个静态类方法
  public class PathUtil { 
      public static String findXML(){ 
        String filePath=PathUtil.class.getClass().getResource("/").getPath();    
        filePath=filePath.substring(1).replace("bin", "src"); 
        filePath=filePath.replace("/", "\");
       // File file=new File(filePath+"applicationContext.xml");
       //测试过 file不为空 
         return filePath+"applicationContext.xml"; }}
再在main方法里调用 
   ApplicationContext ac = new ClassPathXmlApplicationContext(PathUtil.findXML());
可是在cmd命令窗口里用 java -jar fileWatcher.jar 
都会说找不到配置文件请问各位大大正确的写法要怎么写呢?
新人 没有分...
JAR Spring

------解决方案--------------------
这个是因为 classpath 不对,需要修改下 fileWatcher.jar/META-INF/MANIFEST.MF 这个文件,将当前路径添加进去,也就是那个 '.'
例如:

Manifest-Version: 1.0
Class-Path: . test_lib/spring-core-3.2.3.RELEASE.jar test_lib/commons-
 logging-1.1.3.jar test_lib/spring-context-3.2.3.RELEASE.jar test_lib/
 spring-expression-3.2.3.RELEASE.jar test_lib/spring-beans-3.2.3.RELEA
 SE.jar
Main-Class: org.demo.Main



另外有一个简单的办法就是:在 Eclipse 里面 -> Export -> Runnable JAR file -> 选择那个 Copy required libraries into a sub-folder ...