如何在BUCK中添加依赖及版本?引入org.json等库报错的解决办法
Got it, let's sort out how to add the org.json dependency to your Buck project—since you're used to Maven's pom.xml, Buck has its own straightforward approach once you know the steps.
1. Fetch from Maven Central (Most Common)
Buck uses the maven_jar rule to pull remote dependencies directly from Maven repositories, just like Maven does. Add this to your project's BUCK file (root or module-specific, depending on your structure):
maven_jar( name = "org_json", artifact = "org.json:json:20240303", # Swap in the version you need sha1 = "INSERT_SHA1_HASH_HERE", # Optional but recommended for integrity checks )
- The
artifactfollows the samegroupId:artifactId:versionformat as Maven. You can pick any stable version from Maven Central (20240303 is a recent reliable release). - To get the
sha1value, head to the artifact's page on Maven Central and grab the SHA-1 checksum from the "Checksums" section—it ensures you're pulling an unmodified, valid artifact.
2. Link the Dependency to Your Build Target
Once you've defined the remote dependency, you need to attach it to your java_library or java_binary target:
For a Java Library:
java_library( name = "my_project_lib", srcs = glob(["src/main/java/**/*.java"]), deps = [ ":org_json", # Reference the maven_jar we just defined # Add other dependencies here ], )
For a Java Binary:
java_binary( name = "my_project_app", main_class = "com.example.MyMainClass", deps = [":my_project_lib"], # Or directly include :org_json if needed )
Alternative: Use a Local JAR File
If you prefer to use a local copy of the org.json JAR instead of fetching remotely, use the java_import rule:
- Place the JAR in your project (e.g.,
libs/json-20240303.jar) - Add this to your BUCK file:
java_import( name = "org_json_local", jars = ["libs/json-20240303.jar"], )
Then reference :org_json_local in your target's deps list just like the remote version.
Verify the Setup
Run your Buck build command (e.g., buck build :my_project_app) to confirm everything compiles without errors. If you hit missing dependency issues, double-check the artifact coordinates, version number, and that the dependency is correctly added to your target's deps.
内容的提问来源于stack exchange,提问作者R10

