简体   繁体   中英

How to share common files between several projects in Java

Suppose that I have a common directory that contains general-purpose files like FileUtils.java and ImageUtils.java . Also I have two projects that should use these common files. What is the most Java-way to import them into these projects? Just add path manually to the -classpath option when using javac and java ? Build them into one jar file? Or something else?

Just follow simple steps:

1.) Have module say, companyname-commons-util

2.) build to a jar file, companyname-commons-util.jar

3.) Add dependency of this jar into other projects, and just reuse the classes. (maybe maven , gradle or explicitly adding into classpath )

** The same can be reused in other projects as well. Good from maintenance point of view, and keeping project structure intact.

The recommendation would be to create a third project and then use that to generate a JAR file; you can then use that reference in your other projects. If you're using Maven to build them you'd end up with a different module with your common code in place.

Besides the things that have been said; a word of warning: try to slice your projects aka components to be as small as possible.

In other words: before just blindly going forward and pushing all content of your "common" folder into its own project it might be worthwhile to step back and carefully look at

a) the contents of common b) how other projects make use of that source

And theoretically, you match that whole picture with the thing that is called "architecture" (which may or may not exist for your overall "product") to understand where "reality differs from as-it-should-be".

Then, finally, you define one or more projects that cover all (or parts of) your source code in "common"; and then you change your whole infrastructure so that other "dependent" projects do not rely on using your "common" source files but some kind of build artifact.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM