Run main class in test dir from maven with Java agent and Log4J configuration

It took a bit of help from Michal (on this StackOverflow post: Running main method from test class via maven) before I got this right. But here it is:

<profile>
   <id>run-importer</id>
   <properties>
      <loadTimeWeaverArg>-javaagent:"${settings.localRepository}/org/springframework/spring-agent/2.5.6/spring-agent-2.5.6.jar"</loadTimeWeaverArg>
      <log4JConfigArg>-Dlog4j.configuration=file:${project.build.directory}/path/to/log4j.properties</log4JConfigArg>
      <mainClassArg>com.myorg.MyClass</mainClassArg>
      <arg1>foo</arg1>
   </properties>
   <build>
      <plugins>
         <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <goals>
               <goal>exec</goal>
            </goals>
            <configuration>
               <executable>java</executable>
               <classpathScope>test</classpathScope>
               <arguments>
                  <argument>${log4JConfigArg}</argument>
                  <argument>${loadTimeWeaverArg}</argument>
                  <argument>-classpath</argument>
                  <classpath />
                  <argument>${mainClassArg}</argument>
                  <argument>${arg1}</argument>
               </arguments>
            </configuration>
         </plugin>
      </plugins>
   </build>
</profile>

And I run it with the command line: mvn -e exec:exec -Prun-importer

The advantages of this approach:

  • The whole purpose of this profile is to run "special code" that should never be deployed but needs to make use of code in src and test src.
  • It leaves room in case this ever needs to be duplicated, so there is no "competition" regarding what gets run with mvn -e exec:exec.
  • I can specify java agent, log4j and lots of other config using variables that already exist in the pom.
  • I can override any of these arguments on the command line with -Darg1="bar"

Popular Posts