Search code examples
javahibernatemavengradlejava-9

How to depend on java validation api /hibernate modules in java with gradle as build tool?


I have similar question as here. However that question does not mention what build tool he is using and I assume that he is using maven as I didn't have problems with maven when using java 9 modules with it previously.

I am using the hibernate validator and I want to use java 9 modules, so I added a module-info file to the package of the module where I am depending on the validator api (the classes I am using are Validator, ValidatiorFactory , ... from packages like javax.validation)

I searched for these classes and found that they reside in this jar in my project dependencies: validation-api-2.0.1.Final.jar, the classes I am using are inside package validation.

I used the command jar --file=/path-to-the-jar-on-my-pc/validation-api-2.0.1.Final.jar --describe-module in the terminal and got the names of the modules exported from that jar:

No module descriptor found. Derived automatic module.

java.validation@2.0.1.Final automatic
requires java.base mandated
contains javax.validation
contains javax.validation.bootstrap
contains javax.validation.constraints
contains javax.validation.constraintvalidation
contains javax.validation.executable
contains javax.validation.groups
contains javax.validation.metadata
contains javax.validation.spi
contains javax.validation.valueextraction

So now when I put in my module-info file for example requires javax.validation the IDE complains that module is not found . I even added the dependency manually in the project structure (pressing ctrl+shift+alt+s to access it in intellij) where I added it from the path where it is stored in my machine but still same result.

I also tried the help tool from intellij and I found that it added requires java.validation; to my module-info and not requires javax.validation;, but anyway neither of them work.

I searched in pom.xml of that module and found this element <Automatic-Module-Name>java.validation</Automatic-Module-Name>, so now I am almost sure that gradle is causing the problem but I am no expert in gradle and how building tools work, so how can I solve this with staying at using gradle as build tool?


Solution

  • Gradle didn't add proper support for the Java Platform Module System until version 6.4. However, you have to explicitly configure Gradle to work with modules.

    // build.gradle
    java {
        modularity.inferModulePath = true
    }
    

    Though if I'm not mistaken, inferModulePath is true by default as of Gradle 7.0.

    For more information regarding Java modules and Gradle see https://docs.gradle.org/current/samples/sample_java_modules_multi_project.html