问题
I have a project that creates a set of protobuf objects and GRPC stubs.
I have a dependency on a jar with other .proto files in it, that I would like to use in my project.
ie:
project-abc-0.0.1.jar contains a file: /some-types.proto It contains these pieces:
package foo_companyname;
message StatusItem {
string status = 1;
string statusDescription = 2;
}
my project has a build.gradle file where I am trying to import it like so:
buildscript {
dependencies {
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.3'
}
}
dependencies {
compile(group: 'com.companyname', name: 'project-abc', version: '0.0.1')
}
Then, inside my new "enhanced-status.proto" I'm doing this:
import "foo_companyname/some-types.proto";
message EnhancedStatus{
string author = 1;
repeated StatusItem status = 2;
}
If I don't reference the other .proto, everything works fine - I'm able to generate all the correct java any python classes. As soon as I add it, I'm getting this:
Execution failed for task ':generateProto'.
> protoc: stdout: . stderr: foo_companyname/some-types.proto: File not found.
enhanced-status.proto: Import "foo_companyname/some-types.proto" was not found or had errors.
enhanced-status.proto:26:19: "StatusItem" is not defined.
I'm assuming there's some trick to getting gradle or protoc to find .proto sources that are in a jar file? Or do I need to extract the jar file's .proto into my own /proto dir? That would cause a conflict, since the jar has a compiled version of some-types.proto already, and I don't want to compile it again.
回答1:
You need to add the package name foo_companyname for using StatusItem message, try in this way:
import "foo_companyname/some-types.proto";
message EnhancedStatus{
string author = 1;
repeated foo_companyname.StatusItem status = 2;
}
回答2:
Using the google protobuf gradle plugin
plugins {
id 'com.google.protobuf' version "0.8.5"
}
You should just need to specify your dependent jar in the dependencies block (i.e, as a 'protobuf' dependency, not 'compile'):
dependencies {
protobuf "com.companyname:project-abc:0.0.1"
}
回答3:
The Protobuf Plugin for Gradle supports protobuf files in dependencies:
If a compile configuration has a dependency on a project or library jar that contains proto files, they will be added to the
--proto_path
flag of theprotoc
command line, so that they can be imported in the proto files of the dependent project. The imported proto files will not be compiled since they have already been compiled in their own projects.
来源:https://stackoverflow.com/questions/48691843/how-do-i-import-a-proto-file-from-a-dependency-jar-using-gradle