使用 maven 构建 scala 应用程序(其中混合了 java 源代码)

2022-08-31 15:44:06

我有一个应用程序,我希望混合Java和Scala源代码(实际上它将Java应用程序迁移到scala - 但一次有点)。

我可以在IDE中很好地做到这一点,非常好。但是我不确定如何使用maven做到这一点 - scalac可以编译java和scala交织在一起,但是我如何为模块设置maven?

另外,我的 scala 源代码是否必须与 java 不同?


答案 1

使用maven scala插件,像下面这样的配置将适用于混合java和scala源代码的项目(scala源代码当然在/scala目录中,正如其他人所提到的)。

您可以运行运行mvn编译,测试等...一切都将正常工作。非常好(它将首先自动运行scalac)。

对于一个伟大的IDE,IntelliJ 8工作得很好:添加scala插件,然后添加一个scala方面,然后调整scala的编译设置,首先运行scala(如果你与scala和java源代码有循环依赖关系,这一点至关重要)。

<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>demo</groupId>
<artifactId>scala-java-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>scala-java-app</name>
<repositories>
    <repository>
        <id>scala-tools.org</id>
        <name>Scala-tools Maven2 Repository</name>
        <url>http://scala-tools.org/repo-releases</url>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>scala-tools.org</id>
        <name>Scala-tools Maven2 Repository</name>
        <url>http://scala-tools.org/repo-releases</url>
    </pluginRepository>
</pluginRepositories>
<build>
    <plugins>
        <plugin>
            <groupId>org.scala-tools</groupId>
            <artifactId>maven-scala-plugin</artifactId>
            <executions>

                <execution>
                    <id>compile</id>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                    <phase>compile</phase>
                </execution>
                <execution>
                    <id>test-compile</id>
                    <goals>
                        <goal>testCompile</goal>
                    </goals>
                    <phase>test-compile</phase>
                </execution>
                <execution>
                   <phase>process-resources</phase>
                   <goals>
                     <goal>compile</goal>
                   </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.5</source>
                <target>1.5</target>
            </configuration>
        </plugin>
    </plugins>  
</build>
<dependencies>
    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-library</artifactId>
        <version>2.7.2</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
</dependencies>


答案 2

是的,scala部分必须在单独的模块和目录中。Maven认为这样的混合来源是异端邪说。src/main/scala

您可以通过导入 scala maven 插件来启用 scala 编译。“用法”页面就是一个很好的例子。


推荐