r/javahelp • u/Lvl20Rogue • Dec 29 '19
Understanding Maven
So i'm recently getting into maven for the first time in my life. I'm a bit confused and i think it's because i don't really know what maven does. I have this POM.XML file in my project. Do i just add a dependency there and maven will magically find the JAR and download it for me, or do i need to somehow also manually download the JAR and the POM just points at it?
Help would be greatly appreciated!
17
Upvotes
4
u/FrenchFigaro Software Engineer Dec 29 '19
Maven combines two tools: it's a build tool on one hand, and a dependency management tool on the other.
It's also useful in that it gives a structure to your project so that you can share it without having to share the project files specific to your IDE (so that if I prefer eclipse and you prefer IntelliJ, we can use whatever source management tool we like and work collaboratively without too much hassle)
Without a dependency management tool, you have to manually keep track of your dependencies, and of your dependencies' dependencies. This is what is called a dependency tree.
The problem is that for your project to compile and run smoothly, you need to have flat dependencies. Here's an example:
You use a library A, and a library B. These are your dependencies. But library B uses library A as well, and library C. These are B's dependency. B could be packaged in a standalone form that includes A and C.
The problem with that solution is that if you include both B and A, you might run into a conflict. Another one, is that B's binaries are no bigger because they include A and C's binaries. And finally, when you share code, you will either have to provide A and C (which might not be permitted by the licence) or force every new developer on the project to download the right version, which might be a source of error.
What maven does first, is that it flattens the dependency tree. In this case, it sees that you need A and B, and B needs A and C, so it downloads each one only once. As another user explained, it first checks in your local repo, and then it downloads from the distant (which is maven central by default but can be configured to something else).
There still might be some conflicts, for example if your project and library B do not use the same version of library A, but maven has defined behaviour to solve those automatically, or through configuration.
Maven also allows you to define scope to dependencies. For example, if you use Mockito for your unit tests, you can assign it the scope "test", so that the dependency is only used when running the tests, and not included in the final build (jar, war or ear). If your application runs on a server that provides the dependency B, you can assign it the scope "provided", and the dependency will not be included in the final build either.