Exclude all transitive dependencies except from a particular declared dependency

I have a java dropwizard project using gradle 7.3, with a lot of internal libraries as dependencies to the project. The internal libraries pollute my project’s classpath and I want to exclude all transitive dependencies in gradle groovy dsl as below:

configurations.all {
  transitive = false
}

The problem is this would exclude transitives from dropwizard project itself that I would like without declaring them explicitly.

One way is to all transitive = false block to all the internal dependencies but there are so many and that doesn’t seem that elegant and I want to avoid that since I need to add that block every time I add a new dependency.

I basically want to exclude all transitive dependencies from all declared dependencies except from the group “io.dropwizard”.

Is there any way to achieve this with a small block of code in one place? Something like adding a condition for group id in the above configurations.all block or similar?

Also, is there a way to filter transitives based on group id as well? For example, I might want to be able to exclude all transitive dependencies from an internal library except the transitives that belong to the group id com.mycompany . Adding exclude statements for all other dependencies will be very messy in this case, and I need to be aware of the dependencies that I need to exclude.