What are unused/undeclared dependencies in Maven?

2019-03-07 23:33发布

问题:

Maven dependency:analyze complains about the dependencies in my project. How does it determine which are unused and which are undeclared? What should I do about them?

Example:

$ mvn dependency:analyze 
...
[WARNING] Used undeclared dependencies found:
[WARNING]    org.slf4j:slf4j-api:jar:1.5.0:provided
[WARNING]    commons-logging:commons-logging:jar:1.1.1:compile
[WARNING]    commons-dbutils:commons-dbutils:jar:1.1-osgi:provided
[WARNING]    org.codehaus.jackson:jackson-core-asl:jar:1.6.1:compile

...
[WARNING] Unused declared dependencies found:
[WARNING]    commons-cli:commons-cli:jar:1.0:compile
[WARNING]    org.mortbay.jetty:servlet-api:jar:2.5-20081211:test
[WARNING]    org.apache.httpcomponents:httpclient:jar:4.0-alpha4:compile
[WARNING]    commons-collections:commons-collections:jar:3.2:provided
[WARNING]    javax.mail:mail:jar:1.4:provided

Note: A lot of these dependencies are used in my runtime container and I declared them as provided to avoid having the same library on the classpath twice with different versions.

回答1:

Not sure how Maven determines this. It is not required to address all the items reported by this, but this information can be used as appropriate.

Used undeclared dependencies are those which are required, but have not been explicitly declared as dependencies in your project. They are however available thanks to transitive dependency of other dependencies in your project. It is a good idea to explicitly declare these dependencies. This also allows you to control the version of these dependencies (perhaps matching the version provided by your runtime).

As for unused declared dependencies, it is a good idea to remove them. Why add unnecessary dependency to your project? But then transitivity can bring these in anyway, perhaps, conflicting with your runtime versions. In this case, you will need to specify them — essentially to control the version.

By the way, mvn dependency:tree gives the dependency tree of the project, which gives you a better perspective of how each dependency fits in in your project.



回答2:

The answer to:

"How does it determine which are unused and which are undeclared?".

Maven uses Object WebASM framework that analyzes your raw bytecode. It goes through all your classes and then builds a list of all classes that these reference. That is the how.

As to what to do, I would not recommend removing the "unused, declared dependecies" unless you are absolutely sure they actually unused.