如何在Java maven項目中整合Scala代碼

前言:介紹scala

Scala是一個運行在Java JVM上的面向對象的語言。它支持函數編程,在語法上比Java更加靈活,同時通過Akka庫,Scala支持強大的基於Actor的多線程編程。

那麼,我們就不能在新項目中應用和實踐Scala麼?通過我的實踐,我發現其實我們可以通過簡單的Maven配置把Scala集成到我們現有的Java項目中。這樣我們可以很簡單得在Java項目中集成和使用Scala。
在開發之前,我們首先要配置Scala環境。我在Java開發中使用IntelliJ,首先,在IntelliJ中安裝Scala插件。插件安裝好後,我們重啓IntelliJ,這樣我們的運行環境就配置好了。

Java項目添加Scala的步驟

我們用IntelliJ新建一個Maven項目,

添加如下Maven Dependency

<dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>2.10.1</version>
        </dependency>

同時添加如下plugin

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.8.1</version>
                <configuration>
                    <includes>
                        <include>**/*.java</include>
                        <include>**/*.scala</include>
                    </includes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.scala-tools</groupId>
                <artifactId>maven-scala-plugin</artifactId>
                <version>2.15.2</version>
                <executions>
                    <execution>
                        <id>scala-compile-first</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>scala-test-compile</id>
                        <phase>process-test-resources</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

這樣就完成了對我們的Java項目添加Scala的步驟。

在下面的Scala代碼中,我們實現了一個簡單的Servlet返回Hello World:

package weblog.examples.scala

import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.{RequestMapping, RequestMethod}
import javax.servlet.http.{HttpServletRequest, HttpServletResponse}
import java.io.OutputStream
import org.apache.log4j.Logger
import org.apache.commons.io.IOUtils
import HelloWorldServlet._

@Controller
class HelloWorldServlet {
  @RequestMapping(value = Array("/"), method = Array(RequestMethod.GET))
  def helloworld(request: HttpServletRequest, response: HttpServletResponse, outputStream: OutputStream) {
    log.info("helloworld is called")
    response.setStatus(HttpServletResponse.SC_OK)
    IOUtils.write("HELLO WORLD!", outputStream)
    outputStream.flush
    outputStream.close
  }
}

object HelloWorldServlet {
  private var log: Logger = Logger.getLogger(classOf[HelloWorldServlet])
}

當這段代碼通過編譯之後,就會生成和Java一樣的class文件。我們可以看到,用Scala編寫的Servlet代碼更加簡潔,這可以大大提高我們的編程效率。

由於Scala語言普及度的侷限,在項目中普及使用還是很有風險的。但是,在我們編寫Unit Test的過程中,我們可以很好的使用Scala來提高我們的編程效率。

下面是一個用Scala寫的對我們的

HelloWorldServlet進行測試的單元測試的例子:

package weblog.examples.scala

import org.springframework.web.servlet.DispatcherServlet
import org.springframework.mock.web.{MockServletConfig, MockHttpServletResponse, MockHttpServletRequest}
import org.junit.{Assert, Test, After, Before}

class HelloWorldServletTest {
  private var dispatcherServlet : DispatcherServlet = _
  private var httpRequest : MockHttpServletRequest = _
  private var httpResponse : MockHttpServletResponse = _

  @Before
  def before() {
    val config = new MockServletConfig
    config.addInitParameter("contextConfigLocation", "classpath:servlet-context.xml")
    dispatcherServlet = new DispatcherServlet
    dispatcherServlet.init(config)

    httpRequest = new MockHttpServletRequest
    httpResponse = new MockHttpServletResponse
  }

  @After
  def after() {
    dispatcherServlet = null
    httpRequest = null
    httpResponse = null
  }

  @Test
  def testHelloWord() {
    httpRequest.setMethod("GET")
    httpRequest.setRequestURI("/")

    dispatcherServlet.service(httpRequest, httpResponse)

    val response = httpResponse.getContentAsString

    Assert.assertEquals("HELLO WORLD!", response)
  }
}

這段代碼,與Java相比較要簡潔很多,這可以大大提高我們的編程效率。

與完全基於Scala開發相比,

這種Java與Scala的混合開發方式有以下幾個優勢

項目本身還是基於Java的,可以很好的使用現有的Java工具,包括CI繼承,等
混合了Java和Scala,可以使程序員根據自己的需要在不同的情況下選擇更合適的語言
在項目未來的持續維護上,我們不需要使用Scala的專門程序員,即使是完全沒有Scala經驗的Java程序員,也可以進行代碼維護
同時我們還可以用這種混合開發方式,對現有的Java項目進行修改,而不是完全的重寫。希望這種混合開發方式可以幫助希望使用Scala而又在工作中沒有機會的朋友。

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章