This is the 17th day of my participation in the August Challenge

1. What is dependency conflict

Maven is a great dependency management tool, but no good thing is perfect. Maven’s dependency mechanism can lead to Jar package conflicts. For example, your project now uses two Jar packages, A and B. Now A needs to depend on another Jar package C, and B also needs to depend on C. But A depends on version 1.0 of C, and B depends on version 2.0 of C. Maven will download both 1.0 C and 2.0 C to your project, so that there are different versions of C in your project. Maven will decide which version of Jar to use based on the shortest dependency path principle, and the other useless Jar will not be used. This is called dependency conflict.

Most of the time, dependency conflicts probably won’t cause an exception to the system, because Maven always selects a Jar package to use. However, it is not ruled out that in some specific conditions, there will be exceptions similar to the class can not be found, so as long as there is a dependency conflict, in my opinion, it is best to resolve, do not leave a hidden danger to the system.

2. Solutions

The way to resolve dependency conflicts is to use Maven’s ** tag, which needs to be placed inside the ** tag, like this:

< the dependency > < groupId > org. Apache. Logging. Log4j < / groupId > < artifactId > log4j - core < / artifactId > < version > 2.10.0 < / version > <exclusions> <exclusion> <artifactId>log4j-api</artifactId> <groupId>org.apache.logging.log4j</groupId> </exclusion> </exclusions> </dependency>Copy the code

Log4j-core itself relies on log4j-API, but since some other modules also rely on log4j-API and the two versions of log4J-API are different, we use the **** tag to exclude log4j-core from the log4j-API. This way Maven will not download the log4J-API on which log4J-core depends, ensuring that there is only one version of log4J-API in our project.

3, Maven Helper

Looking at this, you might have a question. How do you know which dependent Jar packages conflict in your project? Maven Helper, a plugin for InteliJ IDEA, solves this problem. I won’t go into how to install plugins, but since you already know Maven, I’m sure you can install plugins too.

After the plug-in is installed, we open the POM.xml file with an additional Dependency Analyzer option at the bottom

Click on this option

Find the conflicting Jar packages, right-click, and select Exclude to Exclude the conflicting Jar packages.

4. Tips

In addition to using Maven Helper to check Dependencies, you can also use the Maven dependency diagram provided by IDEA. Open the Maven window and select Dependencies. Then click the icon (Show Dependencies) or use the shortcut key (Ctrl+Alt+Shift+U) to open the Maven dependency diagram

In the figure, we can see that there are some red solid lines. These red solid lines are dependency conflicts, and the blue solid lines are normal dependencies.