首页 > 解决方案 > IntelliJ 不能识别 Scala 项目中的 protobuf 吗?

问题描述

我的 scala 项目中有一个 protobuf 文件src/main/protobuf/datamodel.protoprotoc我正在使用安装在我的 ubuntu 机器上的编译器生成 java 文件。

cd src/
protoc --java_out=main/java main/protobuf/datamodel.proto

数据模型.proto:

syntax = "proto3";
package org.github.felipegutierrez.explore.akka.classic.remote.serialization;
option java_package = "org.github.felipegutierrez.explore.akka.classic.remote.serialization";
option java_outer_classname = "Datamodel";
message OnlineStoreUser {
  int32 userId = 1;
  string userName = 2;
  string userEmail = 4;
  string userPhone = 5;
}
message ProtobufVote {
  string ssn = 1;
  string candidate = 2;
}

所以当我去src包时org.github.felipegutierrez.explore.akka.classic.remote.serialization,相应的文件就在那里。然后我决定使用sbt-protobuf插件。基本上我在plugins.sbt文件中添加了:

addSbtPlugin("com.github.gseitz" % "sbt-protobuf" % "0.6.5")

并在build.sbt文件上:

enablePlugins(JavaAppPackaging, ProtobufPlugin)
sourceDirectories in ProtobufConfig += (protobufExternalIncludePath in ProtobufConfig).value
unmanagedResourceDirectories in Compile += (sourceDirectory in ProtobufConfig).value
libraryDependencies ++= Seq(
  ...
  "com.google.protobuf" % "protobuf-java"  % "3.14.0",
  "com.google.protobuf" % "protoc" % "3.14.0" pomOnly(),
)

当我sbt protobuf:protobufGenerate在项目的根目录上运行时,会创建相应的 java 文件。很好,我可以编译,使用sbt docker:stagesbt docker:publishLocal没有问题。

错误:但是当我点击我的 IntelliJ IDEA Build>Rebuild project我收到错误:

Datamodel is already defined as class Datamodel
public final class Datamodel {

我想这与 IntelliJ + sbt + protobuf 配置有关。Datamodel当我在 IntelliJ中搜索类时,我在目标目录下只找到一个src_managed,这是sbt protobuf:protobufGenerate生成它的地方。

有谁知道我可以在哪里正确配置它并让 IntelliJ 将该类识别为我项目中的唯一一个?

标签: scalaintellij-ideasbtprotocol-buffers

解决方案


我能够通过在以下位置添加这一行来解决这个问题build.sbt

javaSource in ProtobufConfig := ((sourceDirectory in Compile).value / "generated")

并从文件中删除该option java_packagedatamodel.proto

syntax = "proto3";
package org.github.felipegutierrez.explore.akka.classic.remote.serialization;
option java_outer_classname = "Datamodel";
// commented this line because we are using "sbt-protobuf" plugin to generate java file on the specific location
// option java_package = "org.github.felipegutierrez.explore.akka.classic.remote.serialization";
message OnlineStoreUser {
  int32 userId = 1;
  string userName = 2;
  string userEmail = 4;
  string userPhone = 5;
}

现在该命令sbt protobuf:protobufGenerate生成一个源文件,而 IntelliJ 也只看到一个源文件。


推荐阅读