首先用maven创建一个简单的Java application.
mvn archetype:generate -DgroupId=org.freebird.protocolbuffer -DartifactId=sample -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
创建的目录结构如下:
$ tree sample
sample
├── pom.xml
└── src
├── main
│ └── java
│ └── org
│ └── freebird
│ └── protocolbuffer
│ └── App.java
└── test
└── java
└── org
└── freebird
└── protocolbuffer
└── AppTest.java
由于之前Protocol buffer编译器生成的Java文件是外部的,因此需要一个plugin帮助加入到这个项目中来。
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>../../../template/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
并且之前的编译的protocol buffer的java库已经部署在自己的nexus私服上,现在可以使用dependency来引用它。
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.4.1</version>
</dependency>
package org.freebird.protocolbuffer;
import org.freebird.sample.UserProto.User;
import java.io.FileInputStream;
import java.io.IOException;
/**
* Sample!
*
*/
public class App {
public static void main( String[] args ) throws IOException {
System.out.println( "Welcome to the Java sample for protocol buffer!" );
User user = User.parseFrom(new FileInputStream(args[0]));
System.out.println(user.getName());
System.out.println(user.getEmail());
}
}
运行下面的命令(我假定你会使用exec plugin)
mvn clean compile
mvn exec:java
结果如下:
Welcome to the Java sample for protocol buffer!
freebird
shu_chen@esri.com
因此,protocol buffer的跨语言特性相当好用。
本文详细介绍了如何使用Maven创建一个简单的Java应用,并通过ProtocolBuffer进行跨语言的数据交换。通过配置Maven插件和依赖管理,实现了从指定文件读取数据并反序列化为User对象的过程,最终展示了ProtocolBuffer在Java应用中的高效和易用性。
863

被折叠的 条评论
为什么被折叠?



