After you’ve worked with Maven for a while, you’ll eventually find a need to extend it. While there are some means of executing arbitrary code as part of your build, the best way to handle such needs is to create a maven plugin. The task may seem a bit daunting at first, but you’ll learn a lot about how maven works by doing it. Listed below are the properties that you need to define to examine the dependencies of a maven project from within a plugin. The following code would be placed inside a Maven Mojo.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
The @parameter annotation will bind maven properties to the annotated property. You can refer to many properties on common Maven interfaces. The @component annotation binds Plexus components from maven’s DI framework. Unfortunately I’ve yet to find a single, concise documentation source, but the Codehaus Mojo Cookbook and the Maven API doc will point you in the right direction.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Once you have access to all the needed properties, you can use code similar to the above to examine the dependencies of your project. This particular snippet will collect all dependencies and transitive dependencies for artifacts with a group id of “com.mydomain” into the completeDependencies set. GroupIdFilter is a simple implementation of the ArtifactFilter interface. Note that these are the dependencies of the project that the plugin is executing in, not just those of the plugin itself.
The ability to determine all of the transitive dependencies of your project like this can be very powerful. Once you get ahold of an artifact, you can easily create a JarFile and inspect its manifest, entries or whatever you’re interested in. This allows you to do things like create artifacts that contain code or configuration that feeds into your build process, and automatically discover and take action merely by adding them as a project dependency.