ChatGPT解决这个技术问题 Extra ChatGPT

Different dependencies for different build profiles

Is it possible to have a different set of dependencies in a maven pom.xml file for different profiles?

e.g.

mvn -P debug
mvn -P release

I'd like to pick up a different dependency jar file in one profile that has the same class names and different implementations of the same interfaces.

This can be used when targeting different web servers. For example, when building for a JavaEE 5 server, which offers libs such as JAXB, which you should not include in your war file, versus building for a JavaEE 1.4 server, where you should include the JAXB jar.

L
Lii

To quote the Maven documentation on this:

A profile element contains both an optional activation (a profile trigger) and the set of changes to be made to the POM if that profile has been activated. For example, a project built for a test environment may point to a different database than that of the final deployment. Or dependencies may be pulled from different repositories based upon the JDK version used.

(Emphasis is mine)

Just put the dependency for the release profile inside the profile declaration itself and do the same for debug.

<profiles>
    <profile>
        <id>debug</id>
        …
        <dependencies>
            <dependency>…</dependency>
        </dependencies>
        …
    </profile>
    <profile>
        <id>release</id>
        …
        <dependencies>
            <dependency>…</dependency>
        </dependencies>
        …
    </profile>
</profiles>

This method will cause code unresolved in edit mode. If debug is active, the dependency jar of release will be missing, and the code will be error. How to resolve it?
you can set the release specific dependency's scope as 'provided' in the dependency hierarchy and reset the scope to 'compile' in the release profile section. So that the dependency is available for the compilation but not in the final war for 'debug' profile.
IMHO profiles are useless, at least for dependencies: IDEs give errors, dependencies stop resolving, applications are not working in the end. I was expecting more.
佚名

Your groupId, artifactId should be tokenized in your profiles as properties and you can move your dependencies to the generic section.


This would only be the case if you have 1 dependency. If the number of dependencies differ between debug and release just tokenizing won't work. For that matter I would recommend not to tokenize and explicitly define the deps in the profile section.
The other answer didn't work for me, since the default profile dependencies were still included along with other specific profile dependencies. Your answer worked just fine.
@Vlad Did you remove the dependency from the main body of the POM? Otherwise you'll have it twice. (See stackoverflow.com/q/24855678/6944068 about how to make sure one profile is always active.)