-->

Bazel build is not working on from Maven project

2019-08-23 12:11发布

问题:

I'm new to Bazel and learning its build work, currently I am trying to do with bazel build from a Maven project, please advise me how to make it working, thanks.

Here is the WORKSPACE file I am trying to define:

maven_jar(
  name = "junit",
  artifact = "junit:junit:3.8.1",
)

maven_jar(
  name = "log4j1",
  artifact = "org.apache.logging.log4j:log4j-core:2.6.2",
)

maven_jar(
  name = "log4j2",
  artifact = "org.apache.logging.log4j:log4j-api:2.6.2",
)
.....

Here is the BUILD file I am trying to define:

package(default_visibility = ["//visibility:public"])

java_binary(
    name = "everything",
    srcs = glob(["src/main/java/**/*.java"]),
    resources = glob(["src/main/resources/**"]),
     main_class = "src/main/java/com/test/test/test/App",
    deps = [
    "@junit//jar",
    "@log4j1//jar",
    "@log4j2//jar",
    "@jackson//jar",
    "@jsonsimple//jar",
    "@commonsdbutils//jar",
    "@commons//jar",
    "@guava//jar",
    "@poi//jar"],

)

Here is I got Bazel build results:

mbp:bazel_test me$ bazel build //:everything
INFO: Analysed target //:everything (1 packages loaded).
INFO: Found 1 target...
    ERROR: /Users/me/git/test/test/BUILD:4:1: Building everything-class.jar (104 source files) failed (Exit 1)
    src/main/java/com/test/test/test/Testapp.java:13: error: cannot find symbol
    import org.apache.poi.ss.usermodel.Cell;
                                      ^
      symbol:   class Cell
      location: program package org.apache.poi.ss.usermodel
      .....
      Target //:everything failed to build

回答1:

I see two problems here:

  • The main_class attribute should use dots instead of slashes:

 java_binary(
    name = "everything",
    srcs = glob(["src/main/java/**/*.java"]),
    main_class = "src.main.java.com.test.test.test.App",
    ...
  • There's no org.apache.poi.ss.usermodel.Cell class in the poi jar.

Find the jar's name:

$ bazel query --output=build @poi//jar
...
java_import(
  name = "jar",
  visibility = ["//visibility:public"],
  jars = ["@poi//jar:poi-ooxml-3.9.jar"],
  srcjar = "@poi//jar:poi-ooxml-3.9-sources.jar",
)

The package's location is $(bazel info output_base)/external/poi, and now we know (from the srcs attribute in the bazel query output above) that the file is called poi-ooxml-3.9.jar:

$ unzip -l $(bazel info output_base)/external/poi/jar/poi-ooxml-3.9.jar | grep "org.apache.poi.ss.usermodel"
        0  2012-11-26 17:14   org/apache/poi/ss/usermodel/
     2970  2012-11-26 17:14   org/apache/poi/ss/usermodel/WorkbookFactory.class