Search code examples
javamavenspring-booth2dependency-management

Override maven dependency scope in profile


I have spring-boot application based on maven.

I want to have h2 database as dependency only for tests so I have it as follows:

<dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>test</scope>
</dependency>

then I need one maven profile for development which needs h2 as compile or runtime dependency:

    <profile>
      <id>emb</id>
      <activation>
        <activeByDefault>false</activeByDefault>
      </activation>
      <dependencies>
        <!-- Using embedded database in development -->
        <dependency>
          <groupId>com.h2database</groupId>
          <artifactId>h2</artifactId>
          <scope>compile</scope>
        </dependency>
      </dependencies>
    </profile>

But it still failing on "Cannot load driver class: org.h2.Driver" as it is using test scope only.

When I removed test scope specification from dependency it works but it is not what I want since I don't want to have in production.

Any possibility how to rewrite dependency scope based on profile?


Solution

  • Finally I found out that dependency scope override is working correctly.

    Its enough to run maven build with selected profile like this:

    mvn clean install -P emb
    

    You can also check dependency scopes with:

    mvn -P emb dependency:analyze
    

    Problem was with running spring-boot application:

    When I used eclipse/idea or

    mvn spring-boot:run
    

    it fails on missing h2 driver - probably because of running another build without proper profile.

    Solution is to run spring-boot app after maven build with simple java:

    java -jar target/your-app.jar --spring.profiles.active=emb
    

    (spring profile in this case is another story - adding just for full info)