原创转载请注明出处:http://agilestyle.iteye.com/blog/2395056
Project Directory
Maven Dependency
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.fool.protobuff</groupId> <artifactId>protobuff-demo</artifactId> <version>1.0-SNAPSHOT</version> <properties> <protobuf.version>3.4.0</protobuf.version> </properties> <dependencies> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>${protobuf.version}</version> </dependency> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java-util</artifactId> <version>${protobuf.version}</version> </dependency> <dependency> <groupId>com.googlecode.protobuf-java-format</groupId> <artifactId>protobuf-java-format</artifactId> <version>1.4</version> </dependency> </dependencies> <build> <extensions> <extension> <groupId>kr.motd.maven</groupId> <artifactId>os-maven-plugin</artifactId> <version>1.5.0.Final</version> </extension> </extensions> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.5.0</version> <configuration> <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-cpp</goal> <goal>compile-python</goal> </goals> <configuration> <attachProtoSources>true</attachProtoSources> <writeDescriptorSet>true</writeDescriptorSet> <attachDescriptorSet>true</attachDescriptorSet> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
addressbook.proto
syntax = "proto2"; package org.fool.protobuff; option java_package = "org.fool.protobuff.test"; option java_outer_classname = "AddressBookProtos"; message Person { required string name = 1; required int32 id = 2; optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phones = 4; } message AddressBook { repeated Person person = 1; }
mvn clean install
查看生成的AddressBookProtos.java文件
Reference
https://developers.google.com/protocol-buffers/docs/javatutorial
http://www.jianshu.com/p/1538bf85dad1