1.scala和maven如何整合
-
<?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>WordCount2</groupId> <artifactId>WordCount2</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-library</artifactId> <version>2.10.4</version> </dependency> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-compiler</artifactId> <version>2.10.4</version> </dependency> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-reflect</artifactId> <version>2.10.4</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-core_2.10</artifactId> <version>1.5.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.scala-tools</groupId> <artifactId>maven-scala-plugin</artifactId> <version>2.15.2</version> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
最下面的plugin是用来编译scala源代码的,毕竟java与scala是二种不同的语言,有各自的sdk和编译器,所以需要专门的maven插件来处理scala的编译。
项目的目录结构,大体跟maven的默认约定一样,只是src下多了一个scala目录,如下图:
这样,java源代码放在/src/java下,scala源代码放在/src/scala下,管理起来也比较清爽,上图中scala下的Hello.scala源代码如下:
1
2
3
4
5
6
7
|
package yjmyzz class Hello { def sayHello(x : String) : Unit = { println( "hello," + x); } } |
然后java下的HelloWorld.java里就可以调用scala的Hello类:
1
2
3
4
5
6
7
8
9
|
package yjmyzz; public class HelloWorld { public static void main(String[] args){ Hello h = new Hello(); h.sayHello( "scala" ); } } |
2.scala项目maven的编译打包
如果直接运行mvn clean package ,会杯具的发现
[ERROR] /Users/jimmy/Work/IdeaProjects/Default/MyScala/src/main/java/yjmyzz/HelloWorld.java:[7,9] cannot find symbol
[ERROR] symbol: class Hello
[ERROR] location: class yjmyzz.HelloWorld
原因是mvn clean package默认只处理java源代码的编译、打包,而不管scala,所以编译时遇到Hello这个由scala语言编写的class,此时scala还没编译生成class,所以找不到相应的调用入口。
解决办法:
mvn clean scala:compile compile package
如上,在compile前加入scala:compile,这是maven-scala-plugin插件提供的选项,表示编译scala,这样一来,先编译scala,再编译java,最后打包,妥妥滴!