我的需求是把SpringBoot项目打包成一个工具包即SDK包,其他的话只要通过Main方法就可以调用,按网上说法,把所有Maven依赖包及资源都打到一个包中去,然后在Main方法中通过如下获取Bean,
ApplicationContext APPLICATION_CONTEXT3=new ClassPathXmlApplicationContext(new String[]{"*.xml"});
StudentService studentService =APPLICATION_CONTEXT3.getBean("studentService", StudentService.class);
studentService.needMenthod();
结果报找不到依赖包中的类,明明打进去了,结果说找不到。怀疑打包有问题,然后各种度娘,最后发现通过maven-assembly-plugin 可以实现这种效果,如下为Pom中打包配置:
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId> maven-assembly-plugin </artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.cetc.di.App</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
终于不报找不到类了,但是又报另一个错,如下:
org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 107; schema_reference.4: 无法读取方案文档 'http://www.springframework.org/schema/beans/springbeans-3.0.xsd', 原因为 1) 无法找到文档; 2) 无法读取文档; 3) 文档的根元素不是 <xsd:schema>。
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.warning(ErrorHandlerWrapper.java:99)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:433)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:347)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaErr(XSDHandler.java:4166)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaWarning(XSDHan
结果又是各种度娘,发现用上面的方式手动启动Spring容器有问题,改用以下就可以了,
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.setValidating(false);//估计主要是这行代码的作用。
context.load("classpath*:*.xml");
context.refresh();
StudentService studentService = (StudentService ) context.getBean("studentService");
studentService .needMenthod("Hello World !!!!!!!!!");
结果终于成功了,功负不负有心了,折腾了5天,蛋疼及脑壳疼。。。
本文讲述了在将SpringBoot项目打包成SDK Jar时遇到的两个问题:1) 打包后的jar找不到依赖包中的类;2) 使用ClassPathXmlApplicationContext加载XML配置文件时出现SAXParseException。作者通过调整maven-assembly-plugin的配置解决了类找不到的问题,然后通过使用GenericXmlApplicationContext并关闭验证解决了XML解析错误。最终成功运行了SDK Jar中的Main方法。

被折叠的 条评论
为什么被折叠?



