0

Let say that I have defined some bean like that:

@Component
@Validated
public class MyComponent {
    public void someMethod(@NotNull Integer myIntValue) {
        System.out.println(myIntValue);
    }
}

This is packaged into some jar file like: com.comppany:component:1.0.jar

This jar file needs to depend (include?) from:

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
    <version>2.1.0.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
  </dependency>
  <dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.13.Final</version>
  </dependency>
  <dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator-annotation-processor</artifactId>
    <version>6.0.13.Final</version>
  </dependency>

The question is: What if this jar file is added as dependency to another project where there is different JSR-303 validation implementation (Commons validator from apache for example)? Is there a way to protect from this situation? 1. Use one validation impl for "component" module and other for other? 2. or may be validate at compile time (how?) that target which imports "component" module have same JSR-303 validation?

Cherry
  • 31,309
  • 66
  • 224
  • 364
  • maybe excluding the validation dependency of the dependencies declared in pom.xml could help. On [Dependency Exclusions section of maven guides page](https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html) there are details about `exclusions` –  Feb 13 '19 at 15:41

1 Answers1

0

I have seen optional used for this. You'll be able to build the library with the Hibernate validator you specified. Clients using your library will either specify the Hibernate validator dependency explicitly, or a JSR-303 compliant validator library of their choice.

This assumes that the @Validated annotation doesn't explicitly mention the 'hibernate' package in the import statement and instead uses the API.

This may cause the app to not build if the dependency is not supplied, but that might be okay, as it will make the client be explicit with dependency choice.

This SO answer gives more background, and here's the Maven documentation.

The alternative is to leave what you have, and if someone wants to use a different library, they exclude the Hibernate dependency from the dependency on this library, and add their own. This is nice if the client just wants the app to work without having to think about what JSR-303 dependency to use.

Which you choose depends on how you expect folks to use this library.

user944849
  • 14,524
  • 2
  • 61
  • 83