在Java项目中整合Scala
Scala是一个运行在Java JVM上的面向对象的语言。它支持函数编程,在语法上比Java更加灵活,同时通过Akka库,Scala支持强大的基于Actor的多线程编程。具有这些优势,使得我最近很想在一个新的项目中使用Scala,但是在新项目中,抛弃我们常用的Java和C#,而直接使用一门新的语言是很困难的。这不仅包括学习新语言这个过程,未来,更为项目的长期发展和日后的开发和支持增加了很多变数。毕竟一门新的语言是不可能在很短的时间内在行业中达到Java和C#的流行度的。
那么,我们就不能在新项目中应用和实践Scala么?通过我的实践,我发现其实我们可以通过简单的Maven配置把Scala集成到我们现有的Java项目中。这样我们可以很简单得在Java项目中集成和使用Scala。在这篇blog里,我给出一个用Scala实现的Hello World Servlet。项目的代码可以在https://github.com/mcai4gl2/scala-integration中找到。
在开发之前,我们首先要配置Scala环境。我在Java开发中使用IntelliJ,首先,在IntelliJ中安装Scala插件。插件安装好后,我们重启IntelliJ,这样我们的运行环境就配置好了。
我们用IntelliJ新建一个Maven项目,添加如下Maven Dependency:
package weblog.examples.scalaimport org.springframework.web.servlet.DispatcherServletimport 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) }}
与完全基于Scala开发相比,这种Java与Scala的混合开发方式有以下几个优势: