maven filter简介

来源:互联网 发布:java版qq 编辑:程序博客网 时间:2024/05/17 07:56

  本人在最近使用maven时遇到了一个问题,现将解决问题的过程以及maven filter的技巧做简单介绍,希望大家可以多多指正。

问题:使用Mybatis的动态sql进行查找时,无论如何查找结果都为空,查找sql如下所示:

<if test=”name != null and name != ””\>
   and name like CONCAT(‘%’,’${name}’,’%’ )
</if>

查找过程:通过打开sql日志,发现输出的sql中name变量被替换为莫名其妙的文字,打开target/classes/module.report目录下的资源文件,发现在maven打包后的mapper文件中,name已被替换

<if test=”name != null and name != ””>
   and name like CONCAT(‘%’,’ipharmacare-distributed-system’,’%’ )
</if>

结果:查找原因是因为在pom文件中开启了maven filter,而filter plugin会在打包时进行变量替换,具体替换的变量被${}标识,变量可以来自系统变量、应用属性以及命令行输入。

<resource>
 <directory> src/main/resources </directory>
 <filtering> true </filtering>
 …
</resource>

最后将<filtering>设置为false后问题得以解决。

现将maven filter总结如下
1、maven在打包时会copy资源文件,默认情况下mvn会寻找src/main/resources目录,但是有时我们的资源文件可能
并不在该目录下,所以我们可以通过<resources>标签指定maven资源文件的路径,如下所示:

<project>
 <build>
  <resources>
   <resource>
    <directory> [your folder here] </directory>
   </resource>
  </resources>
 </build>
</project>

同样,我们可以显示的通过<includes>,<excludes>标签显示的指定资源文件目录下的哪些文件需要被copy,哪些不需要,具体
语法如下所示:

<resources>
 <resource>
  <directory> [your directory] </directory>
  <includes>
   <include>**/*.xml</include>
   <include> [resource file #n] </include>
  </includes>
  <excludes>
   <exclude>**/*.jpg</exclude>
   <exclude> [non-resource file #n] </exclude>
  </excludes>
 </resource>
</resources>

*注意:匹配符**(可以匹配路径,包含mapper/report/report.xml),*不能包含路径(test.jpg)

2、在我们的资源文件中很可能包含变量,通过${}标识,maven filter plugin可以帮助我们在打包时对变量进行值替换。
例如:我们有资源文件src/main/resources/hello.txt,包含内容如下:

Hello ${name}

pom.xml文件内容如下

<project>
 <name>My Resources Plugin Practice Project</name>
 <build>
  <resources>
   <resource>
    <directory> src/main/resources </directory>
   </resource>
  </resources>
 </build>
</project>

运行maven 打包:

mvn resources:resources

打包后的资源文件输出到路径target/classes/hello.txt,内容如下:

Hello ${name}

注意此时的name变量没有替换,但是如果我们将<filtering>开关打开,

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

同样的运行命令打包,此时的资源文件输出为:

Hello My Resources Plugin Practice Project

我们可以看到maven进行了变量的替换,同样的变量可以来自命令行输入,执行如下命令:

mvn resources:resources -Dname=”world”

打包后的输出为:

Hello world

ibatis小知识点:
1、ibatis中变量标识 # vs $ 的区别

1) #是把传入的数据当作字符串,如#field#传入的是id,则sql语句生成是这样,order by “id”,这样会报错..
2) $传入的数据直接生成在sql里,如#field#传入的是id,则sql语句生成是这样,order by id, 这就对了.
3) #方式能够很大程度防止sql注入,$方式无法方式sql注入.
4) $方式一般用于传入数据库对象.例如传入表名.
5) 一般能用#的就别用$.

0 0
原创粉丝点击