因为项目是spring+mybatis的c/s程序,需要打成jar包到目标服务器上运行,折腾了很久,才将jar包打好,并最终在目标机器上通过 java -jar packagename.jar运行成功。现在具体的pom.xml文件描述一下:
(1)、指定maven在构建时以utf-8编码(前提是你的java文件确实是utf-8编码,否则不用添加)
在pom.xml文件中添加如下节:
<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
(2)、使用maven-shade-plugin插件进行构建,不要使用maven-assembly-plugin进行构建,具体参考:
http://chenzhou123520.iteye.com/blog/1706242
,使用maven-assembly-plugin我确实没有构建成功,遇到的问题和上面的参考资料是一样的,目前也没有能力解决这个问题。具体如下:
<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>1.4</version><executions><execution><phase>package</phase><goals><goal>shade</goal></goals><configuration><transformers><!-- 下面3个transformer如果不加,会在运行的时候报错,至少我的spring+mybatis项目是这样的,一般报错为:Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/context]--><transformerimplementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"><resource>META-INF/spring.handlers</resource></transformer><transformerimplementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"><mainClass>main函数所在的类的全路径名</mainClass></transformer><transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"><resource>META-INF/spring.schemas</resource></transformer></transformers></configuration></execution></executions></plugin></plugins><finalName>packagename(自己填写)</finalName><resources><!-- 下面的resource是自己工程中所需要的配置文件 --><resource><directory>src/main/resources</directory><includes><include>**/*.xml</include></includes></resource><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include></includes></resource><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource></resources></build>
(3)、打包。
直接在idea中点击点击package,然后点击下面的播放按钮进行打包:
如果打包还是不能运行,比如报配置文件找不对,请注意一下,读取jar中的xml文件是用下面这种方式,而不是文件系统下的方式,我也遇到这个问题:
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath*:**/spring-mybatis.xml");
不要使用
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-mybatis.xml");
使用下面这个在intellij idea中调试肯定不会错的,但在java -jar package.jar时会报错。