开发者

Filtering source code in Maven

I wrote a small BeanShell script that replaces "__LINE__" with the actual line number in source code. It works well in Ant.

I am looking for a way to filter source code in Maven so that my BeanShell script can generate a new source 开发者_如何学Gocode directory that then gets compiled.

I know about resource file filtering. Is there any similar facility for source code?


Filtering source code was still tricky some months ago, but there's now a standard plugin at the MOJO project. You can now do that with a classic plugin declaration.

To filter source code (for example, when you'd like to have a constant in your Java code to retrieve the project version or artifactId), you should now use the templating-maven-plugin.

  1. Put your code that should be filtered during the build under src/main/java-templates as you would normally do under src/main/java for non filtered sources. Use ${project.version} or whatever property coming from the POM in your code.

  2. Just put something like:

    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>templating-maven-plugin</artifactId>
      <version>1.0-alpha-3</version> <!-- Be sure to use the last version. Check on the website's plugin -->
      <executions>
          <execution>
          <id>filter-src</id>
          <goals>
              <goal>filter-sources</goal>
          </goals>
          </execution>
      </executions>
    </plugin>
    
  3. Be done :-). The code you put inside src/main/java-templates gets filtered and added to the classpath.

The usage is very straightforward (see the example here).

This respects far better the idea of convention over configuration of Maven. You're basically replacing tens of XML lines and some hacks to get something done cleanly.

Side note: this works fine with Eclipse for example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜