前因
Nutz接触时间了,最近使用NutzBoot开发了个微服务,在准备部署的时候遇上一个问题,NutzBoot在发布时,会将配置文件、模板文件都打包进jar包,那么在后期做细微调整时将涉及到重新发包,本人强伯症,受不了这个,如果项目只是需要对配置做些修改,或者模板做些修改,完全没必要重新打包发布,故而发生了之后的事情 - 改造
过程
怎样把配置文件打包到jar包外面?
修改 pom.xml <build>...</build>
标签内加入配置,过滤resources
目录
<resources> <resource> <directory>src/main/resources</directory> <excludes> <exclude>**/*</exclude> </excludes> <filtering>true</filtering> </resource> </resources>
<build><plugins>...</plugins></build>
标签内加入配置,将配置资源目录编译到jar包外
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <executions> <execution> <id>copy-resources</id> <phase>package</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <encoding>UTF-8</encoding> <outputDirectory> ${project.build.directory} </outputDirectory> <!-- 表示把配置文件拷到和jar包同一个路径下 --> <resources> <resource> <directory>src/main/resources/</directory> </resource> </resources> </configuration> </execution> </executions> </plugin>
此时执行mvn clean;mvn compile;mvn package;
已经可以将资源文件打包到jar包外部了。
那么问题来了,项目如何读取外部资源
首先我是想办法解决beetl模板文件的读取,因为NutzBoot项目没有考虑过外部读取的情况,所以必须经过改造,与@wendal进行讨论后,采取从Setup的init方法着手,手动指定模板读取路径,实现如下:
public class MainSetup implements Setup { @Override public void init(NutConfig nc) { for(ViewMaker maker: nc.getViewMakers()) { if(maker.getClass() == BeetlViewMakerStarter.class) { // 获取BeetlViewMaker对象 BeetlViewMaker beetlViewMaker = (BeetlViewMaker)maker; // 生成FileResourceLoader 从文件系统取资源 FileResourceLoader fileResourceLoader = new FileResourceLoader(); fileResourceLoader.setCharset("UTF-8"); // 设置jar包外部模板目录 fileResourceLoader.setRoot(getBasePath() + File.separator + "template"); // 配置beetlViewMaker使用外部目录读取模板 beetlViewMaker.groupTemplate.setResourceLoader(fileResourceLoader); } } } @Override public void destroy(NutConfig nc) { } // 获取jar包当前目录 static String getBasePath() { String basePath = MainLauncher.class.getProtectionDomain().getCodeSource().getLocation().getPath(); int lastIndex = basePath.lastIndexOf(File.separator); basePath = basePath.substring(0, lastIndex); try { basePath = java.net.URLDecoder.decode(basePath, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return basePath; } }
外部模板读取问题解决,就剩下读取外部配置文件,于是跟@wendal 又进行各种沟通,最后决定修改源码让NutzBoot支持读取外部配置文件,顺便实现了指定配置文件目录自动扫描,详细步骤就不写了,如有兴趣可关注 论坛讨论贴 NutzBoot 如何打包发布
经过修改后,现在NutzBoot支持外部配置方式,比如将application.properties
放在jar包同级目录。 另外application.properties
新增支持配置读取其他配置文件, 如:
nutz.boot.configure.properties.dir=config // 系统将自动扫描jar包同级config目录下所有properties文件进行参数读取
结束语
到此我外部读取参数和模板的需求算是圆满解决,也特别感谢@wendal给予的支持,特此记录