读书人

想把spring配置放在jar包外main方法

发布时间: 2013-08-06 16:47:25 作者: rapoo

【求助】想把spring配置放在jar包外,main方法里该怎么读取写”
如题 main方法里该怎么写才能读取到放在jar包外面的applicationContext.xml呢?
想把spring配置放在jar包外,main方法里该如何读取写”
想把spring配置放在jar包外,main方法里该如何读取写”
上图是文件夹内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 ...


[解决办法]

package src;

import java.net.URL;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class stest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
URL path1= stest.class.getResource("");
String path=path1.toString().substring(path1.toString().indexOf("file"), path1.toString().indexOf("SpringTest"));
ApplicationContext ac=new ClassPathXmlApplicationContext(path+"applicationContext.xml");
}

}

试试这个,我的jdk是1.6。SpringTest是jar包名。我没加log4j
D:\workspace\mywork\SpringTest>java  -jar SpringTest.jar
log4j:WARN No appenders could be found for logger (org.springframework.context.s
upport.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.

读书人网 >J2SE开发

热点推荐