Excluding a dependency in Maven means preventing a specific transitive dependency pulled in by a direct dependency from being added to your project's classpath. This is done with the <exclusions> element nested inside a <dependency> declaration.
Key Points: • Exclusions are declared per-dependency, so the same transitive dependency may need excluding from multiple direct dependencies if they all pull it in. • A common reason to exclude is avoiding version conflicts, such as when two libraries bring in incompatible versions of the same logging framework. • Excluding removes the artifact entirely; if your code still needs it, you must add it back explicitly with your desired version. • mvn dependency:tree is the standard way to find which dependency is pulling in the unwanted transitive artifact before writing the exclusion.
Example: A project using spring-boot-starter-logging alongside another library that transitively pulls in commons-logging can exclude commons-logging from that library to avoid classpath conflicts with SLF4J.
Code Example:
<dependency>
<groupId>com.example</groupId>
<artifactId>some-library</artifactId>
<version>2.1.0</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>Interview Tip: A concise interview answer is:
"You exclude a transitive dependency by adding an exclusions block inside the dependency that's pulling it in, specifying the groupId and artifactId to exclude. This is typically used to resolve version conflicts, like avoiding a duplicate logging implementation on the classpath."