Reputation: 584
Our maven project includes one 3rd third jar, which has two different versions.
A()
removed in version 2)B()
added (not in version 1))How to organize my codes to support 1.0's api and 2.0's api at the same time ?
Upvotes: 0
Views: 292
Reputation: 5440
A possible way of doing this is to have no dependency on library A (not version 1.0, nor version 2.0) in your project.
You need to create three other build (maven for example) projects / artifacts, which will be wrappers for the different library versions.
You'll have :
In the AbstractWrapper, you'll have an interface / abstract class, that reproduce the api from the library A
you want to use. This is the only [of the 3] artifacts that will be declared in the dependencies of your main project. This abstract wrapper do not depend on your project, nor on lib A
.
Then each wrapper will depend on AbstractWrapper (to get the interface definition), and on the A
library, either version 1 or version 2.
The tricky point now is to get the wrapper implementation (that will be available at runtime) to register in your main project. It depends a lot on the packaging and the runtime environnements (standalone jar, osgi bundle, servlet spec 2.5-, servlet spec 3.0+, springframework...), i let you do some research on plugin registration for your specific environnement.
The ugliest thing you could come up with is a Class.forName()
trying both implementation you did, and using the first it finds (casting the class you get to the abstract wrapper interface).
Finally for the clients using the version 1.0 of the lib A
, you tell them to depends on your main project and your wrapper of lib version 1, and the others on your main project and lib version 2.
Upvotes: 2
Reputation: 5168
You can't. But you can exclude one or the other version with the tag like this:
<dependency>
<groupId>sample.ProjectB</groupId>
<artifactId>Project-B</artifactId>
<version>1.0-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>sample.ProjectD</groupId> <!-- Exclude Project-D from Project-B -->
<artifactId>Project-D</artifactId>
</exclusion>
</exclusions>
</dependency>
See the documentation here: https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html
Upvotes: 1