Spring Dependencies in Gradle Can Be Tricky

Spring Dependencies in Gradle Can Be Tricky

Piotr Kubowicz - January 13, 2020

Spring is the most popular Java web framework for many years and Gradle has an established position as a build tool. You might expect it’s easy to find instructions on how to set up those two together — yet the Internet is filled with advice that will get you into trouble. The official Spring documentation does not make the situation any better in this case.

Using Spring in your applications typically means your classpath contains not only Spring Framework itself, but also other Spring projects like Spring Security plus Spring dependencies that are independent libraries. It may require lots of work to get versions of dependencies right, avoiding incompatible versions being used together. So a much better solution is — not to manage all those versions manually and choose a set suggested by Spring. Technically speaking: importing a BOM (bill of materials).

Gradle support for BOM import appeared in April 2018 as a feature preview and officially in release 5.0 ( November 2018), but you can still find articles written in April 2019 claiming that “unfortunately Gradle doesn’t have such built-in functionality, but you can use plugin io.spring.dependency-management”. Why?

As Gradle initially did not have this feature, Spring authors independently created Dependency Management Plugin, which hacks Gradle dependency resolution system to make it import BOMs as Maven does. As the plugin predates native Gradle support by more than a year, it became the solution that is easiest to google. People repeat gossip instead of consulting the up-to-date Gradle documentation.

Troublesome Spring Dependency Management Plugin

Different people suggest to use the plugin in slightly different ways, let’s take a look at probably the most representative one:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath(
          'org.springframework.boot:spring-boot-gradle-plugin:2.1.0.RELEASE')
    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

repositories {
    jcenter()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
}

In the simplest case, the plugin does what it promises, setting a compatible Spring Security version:

% ./gradlew dependencyInsight --dependency=spring-security

> Task :dependencyInsight
org.springframework.security:spring-security-config:5.1.1.RELEASE (selected by rule)

Now let’s imagine a yet another critical security vulnerability is discovered in Jackson Databind, one of the libraries coming with Spring Boot. Currently our project uses Jackson 2.9.7, there is a patched version 2.10.1 and we want to push it to our production instances immediately, without waiting for Spring Framework to release a new version and then Spring Boot to release a new version based on the updated framework. It’s a critical vulnerability, so better not to wait that long!

As far as we know Gradle, the following fragment should do the job:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    constraints {
        implementation('com.fasterxml.jackson.core:jackson-databind:2.10.1') {
            because 'versions below are vulnerable to CVE-2019-16942'
        }
    }
}

Still, let’s double-check we are safe now:

% ./gradlew dependencyInsight --dependency=jackson-databind

> Task :dependencyInsight
com.fasterxml.jackson.core:jackson-databind:2.9.7
   variant "compile" [
      org.gradle.status             = release (not requested)
      org.gradle.usage              = java-api
      org.gradle.libraryelements    = jar (compatible with: classes)
      org.gradle.category           = library (not requested)

      Requested attributes not found in the selected variant:
         org.gradle.dependency.bundling = external
         org.gradle.jvm.version         = 11
   ]
   Selection reasons:
      - Selected by rule
      - By constraint : versions below are vulnerable to CVE-2019-16942

com.fasterxml.jackson.core:jackson-databind:2.9.7
+--- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.9.7
|    \--- org.springframework.boot:spring-boot-starter-json:2.1.0.RELEASE
|         \--- org.springframework.boot:spring-boot-starter-web:2.1.0.RELEASE
|              \--- compileClasspath (requested org.springframework.boot:spring-boot-starter-web)
+--- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.7
|    \--- org.springframework.boot:spring-boot-starter-json:2.1.0.RELEASE (*)
+--- com.fasterxml.jackson.module:jackson-module-parameter-names:2.9.7
|    \--- org.springframework.boot:spring-boot-starter-json:2.1.0.RELEASE (*)
\--- org.springframework.boot:spring-boot-starter-json:2.1.0.RELEASE (*)

com.fasterxml.jackson.core:jackson-databind:2.10.1 -> 2.9.7
\--- compileClasspath

We still use the vulnerable 2.9.7! What happened? We see the constraint we have just typed in Selection reasons, but what is the ‘rule’ there?

The thing is, when you apply Spring’s Dependency Management Plugin to your Gradle project, then in order to be able to understand and control what happens it’s not enough that you know Gradle — you also need to know how the plugin works. For example, a fundamental principle in Gradle dependency management says that in the case of a version conflict, the newer one wins. As we can see here, it’s no longer true after you apply Spring’s plugin. Because the plugin is quite invasive, prepare yourself for bizarre issues if you use it in a more advanced way.

Ok, so how can we fix our issue while still using the plugin? We need to override the BOM property using the plugin-specific syntax (and first find the name of the property controlling version of our dependency):

ext['jackson.version'] = '2.10.1'
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
}

Native Gradle way

Instead of relying on a third-party plugin, simply use the built-in BOM import support:

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.1.0.RELEASE'
}

repositories {
    jcenter()
}

dependencies {
    implementation platform('org.springframework.boot:spring-boot-dependencies:2.1.0.RELEASE')

    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
}

Spring Security dependency is resolved in the same way as when we used the plugin:

% ./gradlew dependencyInsight --dependency=spring-security

> Task :dependencyInsight
org.springframework.security:spring-security-config:5.1.1.RELEASE (by constraint)

but now we can use well-known Gradle mechanisms for controlling transitive dependencies:

dependencies {
    implementation platform('org.springframework.boot:spring-boot-dependencies:2.1.0.RELEASE')

    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    constraints {
        implementation('com.fasterxml.jackson.core:jackson-databind:2.10.1') {
            because 'versions below are vulnerable to CVE-2019-16942'
        }
    }
}

% ./gradlew dependencyInsight --dependency=jackson-databind

> Task :dependencyInsight
com.fasterxml.jackson.core:jackson-databind:2.10.1
   variant "compile" [
      org.gradle.status             = release (not requested)
      org.gradle.usage              = java-api
      org.gradle.libraryelements    = jar (compatible with: classes)
      org.gradle.category           = library (not requested)

      Requested attributes not found in the selected variant:
         org.gradle.dependency.bundling = external
         org.gradle.jvm.version         = 11
   ]
   Selection reasons:
      - By constraint : versions below are vulnerable to CVE-2019-16942
      - By constraint
      - By conflict resolution : between versions 2.10.1 and 2.9.7

Multi-Project Builds

Now let’s compare how both approaches perform in a Gradle build with sub-projects.

Our example project here would consist of the root project exposing REST controllers with Spring Boot and ‘core’ project having no web interface but still using Spring Framework for dependency injection and so on.

With Spring Dependency Management Plugin

In the ’legacy’ single-project build described initially we had:

apply plugin: 'org.springframework.boot'

which served two purposes: allowed to build an executable Spring Boot JAR and provided Spring’s Dependency Management Plugin with information which BOM to choose.

We cannot simply move the single-project configuration to allprojects{} block of the root project:

allprojects {
    apply plugin: 'java'
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'
}

because only the root project contains the main class:

% ./gradlew build
> Task :core:bootJar FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':core:bootJar'.
> Main class name has not been configured and it could not be resolved

What should we do then? Maybe make just the Dependency Management Plugin common?

allprojects {
    apply plugin: 'java'
    apply plugin: 'io.spring.dependency-management'

    repositories {
        jcenter()
    }
}

apply plugin: 'org.springframework.boot'

It also won’t work, because without Spring Boot plugin the source BOM is not configured:

% ./gradlew build
> Task :core:compileJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':core:compileJava'.
> Could not resolve all files for configuration ':core:compileClasspath'.
   > Could not find org.springframework.boot:spring-boot-starter:.
     Required by:
         project :core

How can we solve the problem? The official documentation doesn’t even consider the case of a multi-project build, which is really sad. Googling for an answer might bring you to a working build script like the following one:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath(
          'org.springframework.boot:spring-boot-gradle-plugin:2.1.0.RELEASE')
    }
}

allprojects {
    apply plugin: 'java'
    apply plugin: 'io.spring.dependency-management'

    repositories {
        jcenter()
    }

    dependencyManagement {
        imports {
            mavenBom 'org.springframework.boot:spring-boot-dependencies:2.1.0.RELEASE'
        }
    }
}

apply plugin: 'org.springframework.boot'

dependencies {
    implementation project(":core")
    implementation "org.springframework.boot:spring-boot-starter-web"
}

With Native Gradle BOM Import

Here the root build.gradle is much simpler:

plugins {
    id 'java-library'
    id 'org.springframework.boot' version '2.1.0.RELEASE'
}

allprojects {
    apply plugin: 'java-library'

    repositories {
        jcenter()
    }
}

dependencies {
    implementation project(':core')
    implementation 'org.springframework.boot:spring-boot-starter-web'
}

Since the imported BOM is treated as a regular dependency, it will be propagated transitively. It’s enough to import the Spring BOM once, in core/build.gradle:

dependencies {
    api platform('org.springframework.boot:spring-boot-dependencies:2.1.0.RELEASE')

    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

When using Spring Dependency Management Plugin we are not able to control exclusively the single jackson-databind dependency. By setting the property

ext['jackson.version'] = '2.10.1'

we are actually upgrading version of a group of dependencies at once — and sometimes this is exactly what we want.

How can we achieve a consistent version for a group of dependencies when using the native Gradle BOM import? Spring includes so many Jackson dependencies that it is inconvenient to create a constraint for every single one of them:

+--- org.springframework.boot:spring-boot-starter-json:2.1.0.RELEASE
    +--- org.springframework:spring-web:5.1.2.RELEASE
    +--- com.fasterxml.jackson.core:jackson-databind:2.9.7
    +--- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.9.7
    +--- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.7
    \--- com.fasterxml.jackson.module:jackson-module-parameter-names:2.9.7

Plus this approach would be very error-prone: it would be easy to miss a dependency.

One solution is to create a virtual platform (think of it as of an in-memory BOM) for Jackson, so informing Gradle that artifacts with a group similar to com.fasterxml.jackson should share a version:

dependencies {
    components.all(JacksonAlignmentRule)
    implementation platform('org.springframework.boot:spring-boot-dependencies:2.1.0.RELEASE')

    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    constraints {
        implementation('com.fasterxml.jackson.core:jackson-databind:2.10.1') {
            because 'versions below are vulnerable to CVE-2019-16942'
        }
    }
}

class JacksonAlignmentRule implements ComponentMetadataRule {
    void execute(ComponentMetadataContext ctx) {
        ctx.details.with {
            if (id.group.startsWith('com.fasterxml.jackson')) {
                belongsTo("com.fasterxml.jackson:jackson-platform:${id.version}")
            }
        }
    }
}

Now a single constraint affects all Jackson dependencies:

% ./gradlew dependencyInsight --dependency=jackson-datatype-jdk8

> Task :dependencyInsight
com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.10.1
   variant "compile" [
      org.gradle.status             = release (not requested)
      org.gradle.usage              = java-api
      org.gradle.libraryelements    = jar (compatible with: classes)
      org.gradle.category           = library (not requested)

      Requested attributes not found in the selected variant:
         org.gradle.dependency.bundling = external
         org.gradle.jvm.version         = 11
   ]
   Selection reasons:
      - By constraint : belongs to platform com.fasterxml.jackson:jackson-platform:2.10.1
      - By constraint
      - By conflict resolution : between versions 2.10.1 and 2.9.7

Things are much easier if authors of the library publish their own BOM. In such a case, we simply apply the BOM, which takes care of aligning versions, so we don’t need to declare a virtual platform.

dependencies {
    implementation platform('org.springframework.boot:spring-boot-dependencies:2.1.0.RELEASE')

    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    // updating due to CVE-2019-16942
    implementation platform('com.fasterxml.jackson:jackson-bom:2.10.1')
}

Conclusion

Although Spring Dependency Management Plugin for Gradle is officially recommended by Spring authors and used in many online tutorials, it does not fit Gradle build model very well. The power of inertia causes people to repeat old instructions, ignoring recommendations from the official Gradle documentation. Features recently added to Gradle allow to achieve the same output without including third-party plugins for dependency management and often result in more concise and maintainable build scripts.

About the author

Piotr Kubowicz

Piotr Kubowicz

Software Engineer

Linkedin profile Twitter Github profile

Piotr is a polyglot developer who has been coding in Java for over ten years. He also tried many other languages, from C and Perl to Ruby.
During his time at nexocode, Piotr's primary focus has been on evolving team culture and ongoing projects by developing build automation and systems architecture to ensure delivery is smooth even as project codebases get bigger and more complex. As an active developer in the community, you can notice him speaking at various meetups and conferences.

Tempted to work
on something
as creative?

That’s all we do.

join nexocode

This article is a part of

Zero Legacy
36 articles

Zero Legacy

What goes on behind the scenes in our engineering team? How do we solve large-scale technical challenges? How do we ensure our applications run smoothly? How do we perform testing and strive for clean code?

Follow our article series to get insight into our developers' current work and learn from their experience. Expect to see technical details, architecture discussions, reviews on libraries and tools we use, best practices on software quality, and maybe even some fail stories.

check it out

Zero Legacy

Insights from nexocode team just one click away

Sign up for our newsletter and don't miss out on the updates from our team on engineering and teal culture.

Done!

Thanks for joining the newsletter

Check your inbox for the confirmation email & enjoy the read!

This site uses cookies for analytical purposes.

Accept Privacy Policy

In the interests of your safety and to implement the principle of lawful, reliable and transparent processing of your personal data when using our services, we developed this document called the Privacy Policy. This document regulates the processing and protection of Users’ personal data in connection with their use of the Website and has been prepared by Nexocode.

To ensure the protection of Users' personal data, Nexocode applies appropriate organizational and technical solutions to prevent privacy breaches. Nexocode implements measures to ensure security at the level which ensures compliance with applicable Polish and European laws such as:

  1. Regulation (EU) 2016/679 of the European Parliament and of the Council of 27 April 2016 on the protection of natural persons with regard to the processing of personal data and on the free movement of such data, and repealing Directive 95/46/EC (General Data Protection Regulation) (published in the Official Journal of the European Union L 119, p 1); Act of 10 May 2018 on personal data protection (published in the Journal of Laws of 2018, item 1000);
  2. Act of 18 July 2002 on providing services by electronic means;
  3. Telecommunications Law of 16 July 2004.

The Website is secured by the SSL protocol, which provides secure data transmission on the Internet.

1. Definitions

  1. User – a person that uses the Website, i.e. a natural person with full legal capacity, a legal person, or an organizational unit which is not a legal person to which specific provisions grant legal capacity.
  2. Nexocode – NEXOCODE sp. z o.o. with its registered office in Kraków, ul. Wadowicka 7, 30-347 Kraków, entered into the Register of Entrepreneurs of the National Court Register kept by the District Court for Kraków-Śródmieście in Kraków, 11th Commercial Department of the National Court Register, under the KRS number: 0000686992, NIP: 6762533324.
  3. Website – website run by Nexocode, at the URL: nexocode.com whose content is available to authorized persons.
  4. Cookies – small files saved by the server on the User's computer, which the server can read when when the website is accessed from the computer.
  5. SSL protocol – a special standard for transmitting data on the Internet which unlike ordinary methods of data transmission encrypts data transmission.
  6. System log – the information that the User's computer transmits to the server which may contain various data (e.g. the user’s IP number), allowing to determine the approximate location where the connection came from.
  7. IP address – individual number which is usually assigned to every computer connected to the Internet. The IP number can be permanently associated with the computer (static) or assigned to a given connection (dynamic).
  8. GDPR – Regulation 2016/679 of the European Parliament and of the Council of 27 April 2016 on the protection of individuals regarding the processing of personal data and onthe free transmission of such data, repealing Directive 95/46 / EC (General Data Protection Regulation).
  9. Personal data – information about an identified or identifiable natural person ("data subject"). An identifiable natural person is a person who can be directly or indirectly identified, in particular on the basis of identifiers such as name, identification number, location data, online identifiers or one or more specific factors determining the physical, physiological, genetic, mental, economic, cultural or social identity of a natural person.
  10. Processing – any operations performed on personal data, such as collecting, recording, storing, developing, modifying, sharing, and deleting, especially when performed in IT systems.

2. Cookies

The Website is secured by the SSL protocol, which provides secure data transmission on the Internet. The Website, in accordance with art. 173 of the Telecommunications Act of 16 July 2004 of the Republic of Poland, uses Cookies, i.e. data, in particular text files, stored on the User's end device.
Cookies are used to:

  1. improve user experience and facilitate navigation on the site;
  2. help to identify returning Users who access the website using the device on which Cookies were saved;
  3. creating statistics which help to understand how the Users use websites, which allows to improve their structure and content;
  4. adjusting the content of the Website pages to specific User’s preferences and optimizing the websites website experience to the each User's individual needs.

Cookies usually contain the name of the website from which they originate, their storage time on the end device and a unique number. On our Website, we use the following types of Cookies:

  • "Session" – cookie files stored on the User's end device until the Uses logs out, leaves the website or turns off the web browser;
  • "Persistent" – cookie files stored on the User's end device for the time specified in the Cookie file parameters or until they are deleted by the User;
  • "Performance" – cookies used specifically for gathering data on how visitors use a website to measure the performance of a website;
  • "Strictly necessary" – essential for browsing the website and using its features, such as accessing secure areas of the site;
  • "Functional" – cookies enabling remembering the settings selected by the User and personalizing the User interface;
  • "First-party" – cookies stored by the Website;
  • "Third-party" – cookies derived from a website other than the Website;
  • "Facebook cookies" – You should read Facebook cookies policy: www.facebook.com
  • "Other Google cookies" – Refer to Google cookie policy: google.com

3. How System Logs work on the Website

User's activity on the Website, including the User’s Personal Data, is recorded in System Logs. The information collected in the Logs is processed primarily for purposes related to the provision of services, i.e. for the purposes of:

  • analytics – to improve the quality of services provided by us as part of the Website and adapt its functionalities to the needs of the Users. The legal basis for processing in this case is the legitimate interest of Nexocode consisting in analyzing Users' activities and their preferences;
  • fraud detection, identification and countering threats to stability and correct operation of the Website.

4. Cookie mechanism on the Website

Our site uses basic cookies that facilitate the use of its resources. Cookies contain useful information and are stored on the User's computer – our server can read them when connecting to this computer again. Most web browsers allow cookies to be stored on the User's end device by default. Each User can change their Cookie settings in the web browser settings menu: Google ChromeOpen the menu (click the three-dot icon in the upper right corner), Settings > Advanced. In the "Privacy and security" section, click the Content Settings button. In the "Cookies and site date" section you can change the following Cookie settings:

  • Deleting cookies,
  • Blocking cookies by default,
  • Default permission for cookies,
  • Saving Cookies and website data by default and clearing them when the browser is closed,
  • Specifying exceptions for Cookies for specific websites or domains

Internet Explorer 6.0 and 7.0
From the browser menu (upper right corner): Tools > Internet Options > Privacy, click the Sites button. Use the slider to set the desired level, confirm the change with the OK button.

Mozilla Firefox
browser menu: Tools > Options > Privacy and security. Activate the “Custom” field. From there, you can check a relevant field to decide whether or not to accept cookies.

Opera
Open the browser’s settings menu: Go to the Advanced section > Site Settings > Cookies and site data. From there, adjust the setting: Allow sites to save and read cookie data

Safari
In the Safari drop-down menu, select Preferences and click the Security icon.From there, select the desired security level in the "Accept cookies" area.

Disabling Cookies in your browser does not deprive you of access to the resources of the Website. Web browsers, by default, allow storing Cookies on the User's end device. Website Users can freely adjust cookie settings. The web browser allows you to delete cookies. It is also possible to automatically block cookies. Detailed information on this subject is provided in the help or documentation of the specific web browser used by the User. The User can decide not to receive Cookies by changing browser settings. However, disabling Cookies necessary for authentication, security or remembering User preferences may impact user experience, or even make the Website unusable.

5. Additional information

External links may be placed on the Website enabling Users to directly reach other website. Also, while using the Website, cookies may also be placed on the User’s device from other entities, in particular from third parties such as Google, in order to enable the use the functionalities of the Website integrated with these third parties. Each of such providers sets out the rules for the use of cookies in their privacy policy, so for security reasons we recommend that you read the privacy policy document before using these pages. We reserve the right to change this privacy policy at any time by publishing an updated version on our Website. After making the change, the privacy policy will be published on the page with a new date. For more information on the conditions of providing services, in particular the rules of using the Website, contracting, as well as the conditions of accessing content and using the Website, please refer to the the Website’s Terms and Conditions.

Nexocode Team

Close

Want to be a part of our engineering team?

Join our teal organization and work on challenging projects.

CHECK OPEN POSITIONS