maven应用(一)--- 基本使用

默认情况下,maven会打包src/main/java下java文件编译后的classes与src/main/resources文件夹下的资源到jar的根目录,相对路径不变。

在打包应用时,若是想要打包源码,可以添加一个resources标签如:

  	<resources>
  		<resource>
  			<directory>src/main/java</directory>
  		</resource>
  	</resources>

当然需要在不影响其他资源正常打包的情况下,添加了java文件夹的资源,会使得src/main/resources文件夹下的资源不被打包。此时若要加入resources文件夹下的资源可以再添加一个resource标签到resources标签下,如:

  	<resources>
  		<resource>
  			<directory>src/main/java</directory>
  		</resource>
  		<resource>
  			<directory>src/main/resources</directory>
  		</resource>
  	</resources>

resource下exclude标签使用:

  		<resource>
  			<directory>src/main/resources</directory>
  			<excludes>
  				<exclude>*</exclude>
  			</excludes>
  		</resource>

通配符*会使得resources根文件夹下的文件不被打包,但是resources文件夹下的子目录及子目录下的文件还是会被打包。

通配符*/*会使得resources文件夹下的二级子目录下的文件不被打包。

通配符**/*会使得resources文件夹下的所有文件不被打包。

若是在resource标签下只使用了includes标签,则只会包含include标签下的文件,如:

  		<resource>
  			<directory>src/main/resources</directory>
  			<includes>
  				<include>log.properties</include>
  			</includes>
  		</resource>

如上,只会打包resources文件夹根路径下的log.properties文件,对于resources下的其他文件及文件夹不被打包。

同时使用include与exclude标签,冲突的部分以exclude为准(冲突的部分不被打包),如:

  		<resource>
  			<directory>src/main/resources</directory>
  			<includes>
  				<include>log.properties</include>
  			</includes>
  			<excludes>
  				<exclude>log.properties</exclude>
  			</excludes>
  		</resource>

如上,log.properties文件将不被打包。

filtering标签的使用可以使得maven将pom中定义的常量,替换到properties等文件中,如下:

	<properties>
		<dd>value</dd>
	</properties>

	<build>
		<resources>
			<resource>
				<directory>src/main/java</directory>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>
	</build>

在log.properties中用占位符${key}来让maven将对应的值替换掉,log.properties文件:

cc=${dd}

解压打包的jar文件,可以看到log.properties文件的内容为:

cc=value

注意:若是${dd}在maven找不到dd对应的值,则maven不会对其进行替换处理,结果会为:

cc=${dd}

maven查找常量配置的地方有:The property can be one of the values defined in your pom.xml, a value defined in the user's settings.xml, a property defined in an external properties file, or a system property.

参考:

http://maven.apache.org/guides/getting-started/index.html#How_do_I_add_resources_to_my_JAR

在这里感慨一下官方文档的简洁明了,看了一些博客,总是感觉晦涩难懂(别人看我写的应该也有这种感觉),但是官方文档真的是言简意赅,切中要害。

猜你喜欢

转载自blog.csdn.net/hurricane_li/article/details/80469622