1. 程式人生 > >Eclipse下Java+Scala混合程式設計的Maven專案

Eclipse下Java+Scala混合程式設計的Maven專案


By Adrian Null

Introduction

Maven is a build/project management tool. It favours “convention over configuration”; it can greatly simplify builds for “standard” projects and a Maven user can usually understand the structure of another Maven project just by looking at its pom.xml (Project Object Model). Maven is a plugin-based architecture, making it easy to add new libraries and modules to existing projects. For example, adding a new dependency usually involves only 5 extra lines in the pom.xml

. These “artifacts” are downloaded from repositories such as The Central Repository.

You can also check out the official example project which uses the same Scala plugin we will show here.

Jumping Ahead

If you’re familiar with Maven, you can go ahead with the Scala Maven Plugin.

The Scala Maven Plugin

We’ll be using the Scala Maven Plugin (GitHub repowebsite) (formerly known as the maven-scala-plugin; renamed to honour the new naming policy where only Maven core plugins are prefixed with “maven”), by far the dominant plugin for Scala projects. Note: the plugin includes Scala from the Central Repository so there’s no need to install it yourself if you’re compiling with Maven.

Getting Maven

Linux (Debian)

On Debian and Debian-derivatives, Maven is usually available via apt-get. Just do (sudo) apt-get install maven and you’re good to go.

OSX

OSX prior to 10.9 (Mavericks) comes with Maven 3 built in. If you don’t have it, you can get it with the package managers MacPortsHomebrew, or Fink. The Scala Maven Plugin requires Maven 3.0+

Manually (Red Hat Linux, OSX, Windows)

You can download Maven from its Apache homepage. After extracting it (tar -zxvf apache-maven-X.X.X-bin.tar.gz, or use something like 7-zip) to your directory of choice (on Linux and OSX, Unix-like systems, I like to put them in /opt/. On Windows I would probably put this inC:/), you need to add Maven to your environment Path variable:

  • Linux/OSX (option 1): Create a symlink to /usr/bin, which is already on your Path
    • ln -s /usr/bin/mvn /opt/apache-maven-X.X.X/bin/mvn
  • Linux/OSX (option 2): Add the Maven bin folder directly to your path, using your shell configuration file (e.g. ~/.bash_profile)
    • Add export PATH=$PATH:/opt/apache-maven-X.X.X/bin to .bash_profile (or whatever profile for the shell you use)
    • Example: echo "export PATH=$PATH:/opt/apache-maven-X.X.X/bin" >> ~/.bash_profile
  • Linux/OSX (option 3): Make a mvn shell script in an existing path location
    • Example: you have $HOME/bin in your path
    • Put the folder you extracted in $HOME/bin (mv apache-maven-X.X.X "$HOME/bin/")
    • Create a file mvn in $HOME/bin
    • Add "$HOME/bin/apache-maven-X.X.X/bin/mvn" [email protected] to it, and chmod u+x mvn to make it executable
    • This is probably the least intrusive way; $HOME/bin is usually added to the user’s path by default, and if not, it’s a useful thing to do/have anyways. The shell script simply invokes the Maven location (which is at some other location) and passes on the arguments
  • Windows
    • Hit Start. Right click on “My Computer” and go to “Properties”
    • This should bring you to “Control Panel -> System and Security -> System”, giving an overview of your computer
    • On the left sidebar there should be four options; click on “Advanced system settings” (fourth one)
    • Under the “Advanced” tab, hit “Environment Variables…” in the bottom right
    • Note: I recommend creating/editing your User variables (top box). You can do the same with System variables though (bottom box)
    • Create a new variable called “MAVEN3_HOME”. Point this to your Maven folder (e.g.C:\apache-maven-X.X.X). Use backslashes to be safe, and do not include a trailing slash
    • Create a new variable called “MAVEN3_BIN” with this value: %MAVEN3_HOME%\bin
    • Edit your Path variable: being careful not to change anything else, append ;%MAVEN3_BIN%to it
    • You’ll need to restart cmd to see these changes

Creating Your First Project

The easiest way to create new projects is using an “archetype”. An archetype is a general skeleton structure, or template for a project. Think back to “convention over configuration”; in our case, the Scala Maven Plugin provides an archetype for scala projects.

You run the archetype plugin like this:

  1. mvn archetype:generate

If this is your first time, you’ll notice that Maven is downloading many jar files. Maven resolves dependencies and downloads them as needed (and only once). Right now, Maven is downloading its core plugins.

Afterwards, it should give you a list of archetypes (in the hundreds). The Scala Maven Plugin was 339 on my list: “net.alchim31.maven:scala-archetype-simple (The maven-scala-plugin is used for compiling/testing/running/documenting scala code in maven.)”. You can type “scala” (or something else) to filter the results. As of 2015 January 27, there you can choose version 3.1.4 or 3.1.5 of this plugin; you should choose the latest

  1. Choose net.alchim31.maven:scala-archetype-simple version:
  2. 1:1.4
  3. 2:1.5

Next, Maven will ask you for a groupId, artifactId, and package. You can read the guide to naming conventions, but in short:

  • groupId: inverted domain name (e.g. com.my-organization)
  • artifactId: project name (e.g. playground-project)
  • version: anything you want, but I recommend you read and follow the guidelines for Semantic Versioning (e.g. 0.0.1)
  • package: the default is the groupId, but you can change this (e.g. com.my-organization)

The groupId and artifactId together should serve as a globally unique identifier for your project

When it’s done, you should see a new folder named with the artifactId. cd into it and run:

  1. mvn package

You’ll see Maven downloading dependencies including the Scala library (as mentioned above),JUnitScalaTest, and Specs2 (the latter three are test frameworks; the archetype includes an example “Hello world” program, and tests with each of the frameworks).

Explaining this Archetype

In your project root, you’ll see a pom.xmlsrc folder, and target folder (target folder only appears after building). Note: this archetype also includes a .gitignore

Inside the src folder you’ll see main and testmain includes your application code, and testincludes your test suites. Inside each of those you’ll find a scala folder, followed by your package structure (actually, test/scala includes a sample package, but you should replace this with your own package and tests). If you want to mix Scala and Java source code, simply add a java folder inside main or test.

target includes generated/built files, such as .class and .jar files. You can read aboutpom.xml at the Maven page.

Example structure:

  • pom.xml
  • src
    • main
      • scala
        • com/my-package/… *.scala
      • java
        • com/my-package/… *.java
    • test
      • scala
        • com/my-package/… *.scala
      • java
        • com/my-package/… *.java
  • target …

Again, you can read more about the Scala Maven Plugin at its website.

Creating a Jar

By default the jar created by the Scala Maven Plugin doesn’t include a Main-Class attribute in the manifest. I had to add the Maven Assembly Plugin to my pom.xml in order to specify custom attributes in the manifest. You can check the latest version of this plugin at the project summary or at The Central Repository

  1. <project ...>
  2. <modelVersion>X.X.X</modelVersion>
  3. ...
  4. <licenses>
  5. ...
  6. </licenses>
  7. <properties>
  8. ...
  9. </properties>
  10. <dependencies>
  11. ...
  12. </dependencies>
  13. <build>
  14. ...
  15. <plugins>
  16. ...
  17. <plugin>
  18. <groupId>org.apache.maven.plugins</groupId>
  19. <artifactId>maven-assembly-plugin</artifactId>
  20. <version>2.4</version>
  21. <configuration>
  22. <descriptorRefs>
  23. <descriptorRef>jar-with-dependencies</descriptorRef>
  24. </descriptorRefs>
  25. <archive>
  26. <manifest>
  27. <mainClass>com.your-package.MainClass</mainClass>
  28. </manifest>
  29. </archive>
  30. </configuration>
  31. <executions>
  32. <execution>
  33. <phase>package</phase>
  34. <goals>
  35. <goal>single</goal>
  36. </goals>
  37. </execution>
  38. </executions>
  39. </plugin>
  40. </plugins>
  41. </build>
  42. </project>

After adding this, mvn package will also create [artifactId]-[version]-jar-with-dependencies.jar under targetNote: this will also copy the Scala library into your Jar. This is normal. Be careful that your dependencies use the same version of Scala, or you will quickly end up with a massive Jar.

Useful commands

  • mvn dependency:copy-dependencies: copy all libraries and dependencies to thetarget/dependency folder
  • mvn clean
  • mvn package: compile, run tests, and create jar

Integration with Eclipse (Scala IDE)

There are instructions at the Scala Maven Plugin FAQs, but I thought I’d expand a bit. The maven-eclipse-plugin is a core plugin (all plugins prefixed with “maven” are, and are available by default) to generate Eclipse configuration files. However, this plugin does not know about our new Scala source files. We’ll be using the build-helper-maven-plugin to add new source folders:

  1. ...
  2. <plugin>
  3. <groupId>org.codehaus.mojo</groupId>
  4. <artifactId>build-helper-maven-plugin</artifactId>
  5. <executions>
  6. <execution>
  7. <id>add-source</id>
  8. <phase>generate-sources</phase>
  9. <goals>
  10. <goal>add-source</goal>
  11. </goals>
  12. <configuration>
  13. <sources>
  14. <source>src/main/scala</source>
  15. </sources>
  16. </configuration>
  17. </execution>
  18. <execution>
  19. <id>add-test-source</id>
  20. <phase>generate-sources</phase>
  21. <goals>
  22. <goal>add-test-source</goal>
  23. </goals>
  24. <configuration>
  25. <sources>
  26. <source>src/test/scala</source>
  27. </sources>
  28. </configuration>
  29. </execution>
  30. </executions>
  31. </plugin>
  32. ...

After adding that to your pom.xml:

  1. Run mvn eclipse:eclipse - this generates the Eclipse project files (which are already ignored by our archetype’s .gitignore)
  2. Run mvn -Declipse.workspace="path/to/your/eclipse/workspace" eclipse:configure-workspace - this adds an M2_REPO classpath variable to Eclipse
  3. Run mvn package to ensure you have all the dependencies in your local Maven repo

Unfortunately, the integration isn’t perfect. Firstly, open up the generated .classpath file (it will be hidden by default as it’s a dotfile, but it should be in your project root directory; where you ran mvn eclipse:eclipse). You should see something like this near the top.

  1. <classpathentrykind="src"path="src/test/scala"output="target/test-classes"including="**/*.java"/>
  2. <classpathentrykind="src"path="src/main/scala"including="**/*.java"/>

Change the *.java to *.scala (or duplicate the lines and change them to *.scala if you also have Java sources).

Secondly, open the .project eclipse file (again, in the same folder). Change <buildSpec> and<natures> to look like this. Now Eclipse knows to use the Scala editor and it won’t think that everything is a syntax error.

  1. <buildSpec>
  2. <buildCommand>
  3. <name>org.scala-ide.sdt.core.scalabuilder</name>
  4. </buildCommand>
  5. </buildSpec>
  6. <natures>
  7. <nature>org.scala-ide.sdt.core.scalanature</nature>
  8. <nature>org.eclipse.jdt.core.javanature</nature>
  9. </natures>

Finally, in Eclipse, under “File” choose “Import…” and find your project.

Using m2eclipse-scala for Eclipse integration

m2eclipse-scala is a work in progress, and their website/repository may have updated information. It aims to ease integration between m2eclipse and Scala IDE for Eclipse.

Under “Help -> Install New Software”, enter “http://alchim31.free.fr/m2e-scala/update-site” and hit enter. You should see “Maven Integration for Eclipse -> Maven Integration for Scala IDE”.

Afer it installs, go to “New -> Project -> Other” and select “Maven Project”. Search fo “scala-archetype” choose the one with the group “net.alchim31.maven”. The wizard will more or less guide you through what was done with mvn archetype:generate above, and you should end up with a new Scala project!

To import an existing project, simply go to “File -> Import -> Existing Maven Project” and find the directory containing your project.

Adding Dependencies

The first thing I do is look for “Maven” in the project page. For example, Google’s [Guava] page includes Maven Central links. As you can see in the previous link, The Central Repository conveniently includes the snippet you have to add to your pom.xml on the left sidebar.

If you can’t find Maven information at the project page, try a Google search for “[project name] maven”. Sometimes, you still won’t find anything. For scopt (Scala command line option parser), I couldn’t find the latest version from Google. However, manually searching The Central Repository did

Afterwards, running

  1. mvn package

Will download any new dependencies before packaging

Other Useful Reading

I’m not going to explain all of Maven in this tutorial (though I hope to add more in the future, because I do feel that the resources are a bit scattered), so here are some useful articles: - Maven Lifecycle (explanation of goals like clean, package, install)

原文連結: http://docs.scala-lang.org/tutorials/scala-with-maven.html 

相關推薦

EclipseJava+Scala混合程式設計Maven專案

By Adrian Null Introduction Maven is a build/project management tool. It favours “convention over configuration”; it can greatly simplify builds for

Eclipse建立一個新的Maven專案

首先在電腦上配置好Maven環境 第一步:在Eclipse中選擇建立Maven Project Next Next Finish 建立好後項目結構如下: 第二步:講專案轉為Web專案,右鍵專案點選properties 進行如下操作: 選擇OK後項目結構變為

Java Scala 混合程式設計導致 編譯失敗 ,【找不到符號】問題解決

大致就是 工程裡分了 java 程式碼 和 scala 程式碼。 然後在java程式碼中 引用了 scala 的程式碼。  執行不報錯。  但是打包就是一直報錯。 [ERROR] Failed to execute goal org.apache.maven.plug

IDEA Java/Scala混合專案maven打包

轉自:http://www.voidcn.com/blog/rongyongfeikai2/article/p-5966631.html 1.在建立Maven專案時,選擇骨架為maven-archetype-quickstart 2.pom檔案內容為: <

EclipseJava Build PathLibraies中添加 Maven dependencies 失敗解決方案

進行 log yun finish 生成 失敗 工程 next uil 當maven 倉庫有jar時,tomcat生成時總是報javaclassno..........無這個文件;用一下方法 轉載:http://bugyun.iteye.com/blog/2311848

Eclipse中啟動Tomcat時(MAVEN專案),報錯:Could not publish to the server. java.lang.IndexOutOfBoundsException的解決過程

Eclipse中啟動Tomcat時(MAVEN專案),報錯:Could not publish to the server. java.lang.IndexOutOfBoundsException,tomcat啟動失敗,   原因:該MAVEN專案下載的本地jar包存在下載失敗的情況 &nbs

Eclipsejava專案的GBK編碼程式碼檔案轉換為UTF-8編碼的實現程式碼

String srcDirPath = "D:\\work\\SVN\\Service";   String utf8DirPath = "D:\\work\\SVN\\Service2";          Collection<File> javaGbkFil

自學基於eclipsejava程式設計——Eclipse開發環境Java視覺化程式設計(第五課)

大家都知道在做Android開發設計GUI時,要新增Android元件可以把元件拖到手機螢幕上,這樣會自動生成程式碼,而不需要自己一個個地把要新增的元件用程式碼生成。其實,Java開發也是可以這樣的。這裡就說一下Eclipse開發環境下Java視覺化程式設計。首先開啟eclip

原生EclipseJava服務器調試的一個問題

item org trac plugin bind aced works href box 當你對Server的配置修改以後,最好到 workspacedir\.metadata\.plugins\org.eclipse.wst.server.core\tmp0目

Eclipse中的新匯入的Maven專案出現紅色歎號以及舊的Maven專案無語法錯誤卻顯示紅叉的解決辦法

問題:   從svn或者本地將maven工程匯入到自己的IDE開發環境後,Maven工程上帶有紅色的感嘆號報錯資訊,其他的沒有紅×報錯。之後其他的Maven專案無語法錯誤卻顯示紅叉,如下圖所示:    根據問題提示可知,這是因為Maven工程沒有自動編譯而導致,我們選中出現問題的專案 --> 右鍵

eclipse找不到server選項maven專案部署tomcat

找到Help->InstallNew Software->" kepler" repository(http://download.eclipse.org/releases/kepler)->Web,XML,  Java EE and OSGi Ent

EclipseJava Card開發總結

近來專案要做CPU卡的開發,如果用真實的CPU卡測試,多次操作錯誤後卡會被鎖死,既浪費資源也不利於開發。因此想到是否有模擬的智慧卡操作呢,網上一搜還真有,用Java模擬智慧卡,叫做“Java Card”開發。 環境搭建 網上介紹的資料比較亂,大體歸納起來主要是給Eclipse安

Eclipse找不到“新建Web專案

之前一直用Netbeans做Web專案,最近因為重灌了一下MySQL,刪除了登錄檔,直接把電腦搞崩掉了。後來尋思著直接換Eclipse吧,然後就遇到了各種問題。 第一個問題就是想要建立一個Web專案,但是在new裡面找不到,後來看部落格,問度娘才解決。下面就是

[JAVA IDEA]在使用maven專案中,無法讀取resources資料夾中的配置檔案的一種解決方案

1、在通過配置檔案來連線資料庫時,在resouces檔案中放入了db.properties配置檔案,但無法正常讀取到  讀取配置檔案資訊的程式碼: InputStream input=JdbcUtil.class.getClassLoader().getResourceAsStream("db.prope

Eclipse使用:從git克隆maven專案

步驟:1.克隆maven專案              2.把專案convert to maven專案 1.匯入專案從git上 2.填寫專案URL和git賬號和密碼 3.選擇分支 4.填寫下載的位置 4.等待下載 5.next 6.填寫專案在eclipse中的

eclipse裡從SVN匯出的Maven專案,沒有“Maven Dependencies ”

本人遇到的問題就是這個問題,在同事的幫忙下才解決的問題,發現問題的方法是: 通過 右鍵-->run as -->maven clean    發現clean不成功,說是缺少jar包,但是專案卻不自動下載,這個問題就比較尷尬了,所以jar包都沒有,也就沒有Maven Dependencies。

Eclipsejdk、tomcat、maven及一些基本配置

1.設定編碼格式為utf-8 Window-Preferences-General-Workspace-Other,選擇UTF-8 2.配置JDK 2.1 Window-Preferences-Java-Installed JREs,選擇Add 2.2 選擇Standard VM-next

MavenEclipse整合和構建多模組Maven專案

最近在工作中越來越經常的用到了Maven作為專案管理和Jar包管理和構建的工具,感覺Maven的確是很好用的。而且要將Maven的功能最大發揮出來,多模組是一個很好的整合例子。 一個Maven專案包括一個MavenProject和多個MavenModule 下面用一個

Eclipse Java工程的打包與釋出

一、建立清單檔案 MANIFEST.MF 在需要打包的工程中建立MANIFEST.MF檔案內容如下: Manifest-Version: 1.0 Main-Class: com.lijia.tes

Eclipse中從svn中檢出maven專案

相信很多初學者都遇到過Eclipse中從SVN檢出Maven專案之後看到的目錄結構並不是Maven目錄結構;或者只能先用SVN將Maven專案簽入到本地,然後再用Eclipse匯入Maven專案,但是