What are Maven goals and phases and what is their difference?

Goals are executed in phases which help determine the order goals get executed in. The best understanding of this is to look at the default Maven lifecycle bindings which shows which goals get run in which phases by default. The compile phase goals will always be executed before the test phase goals, which will always be executed before the package phase goals and so on.

Part of the confusion is exacerbated by the fact that when you execute Maven you can specify a goal or a phase. If you specify a phase then Maven will run all phases up to the phase you specified in order (e.g. if you specify package it will first run through the compile phase and then the test phase and finally the package phase) and for each phase it will run all goals attached to that phase.

When you create a plugin execution in your Maven build file and you only specify the goal then it will bind that goal to a given default phase. For example, the jaxb:xjc goal binds by default to the generate-resources phase. However, when you specify the execution you can also explicitly specify the phase for that goal as well.

If you specify a goal when you execute Maven then it will run that goal and only that goal. In other words, if you specify the jar:jar goal it will only run the jar:jar goal to package your code into a jar. If you have not previously run the compile goal or prepared your compiled code in some other way this may very likely fail.

Leave a Comment