Integrate Scala in Java Projects

Source: Internet
Author: User

Scala is an object-oriented language running on Java JVM. It supports function programming and is more flexible in syntax than Java. At the same time, through the Akka library, Scala supports powerful Actor-based multi-thread programming. With these advantages, I recently wanted to use Scala in a new project, but in the new project, we abandoned the common Java and C #, however, it is very difficult to directly use a new language. This includes not only the process of learning new languages, but also the long-term development of projects and the Development and support in the future. After all, it is impossible for a new language to reach Java and C # popularity in the industry within a short period of time. So, cannot we apply and practice Scala in new projects? Through my practice, I found that Scala can be integrated into our existing Java project through simple Maven configuration. In this way, we can easily integrate and use Scala in Java projects. In this blog, I will provide a Hello World Servlet implemented using Scala. The project code can be found at https://github.com/mcai4gl2/scala-integration. Before development, we must configure the Scala environment. I use IntelliJ in Java Development. First, install the Scala plug-in IntelliJ. After the plug-in is installed, restart IntelliJ, so that the runtime environment is ready. We use IntelliJ to create a Maven project and add the following Maven Dependency: [html] <dependency> <groupId> org. scala-lang </groupId> <artifactId> scala-library </artifactId> <version> 2.10.1 </version> </dependency> Add the following plug-ins at the same time: [html] <plugin> <groupId> org. apache. maven. plugins </groupId> <artifactId> maven-surefire-plugin </artifactId> <version> 2.8.1 </version> <configuration> <des> <include> **/*. java </include> <include> **/*. scala </in Clude> </shortdes> </configuration> </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> <id> scala-test-compile </id> <phase> process-test-resources </phase> <goals> <goal> testCompil E </goal> </goals> </execution> </executions> </plugin> completes the process of adding Scala to our Java project. In the following Scala code, we implement a simple Servlet to return Hello World: [plain] 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])} after this code is compiled, the same class file as Java will be generated. We can see that the Servlet code written in Scala is more concise, which can greatly improve our programming efficiency. Due to the limitations of Scala language popularity, it is still very risky to popularize and use Scala in projects. However, while writing Unit Test, we can use Scala to improve programming efficiency. The following is an example of a unit test written in Scala to test our HelloWorldServlet: [plain] 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)} This code is much simpler than Java, which can greatly improve our programming efficiency. Compared with Scala-based development, this Java-Scala hybrid development method has the following advantages: the project itself is still based on Java, and the existing Java tools, including CI inheritance, can be well used, by combining Java and Scala, programmers can choose a more appropriate language based on their own needs for the future continuous maintenance of the project, we don't need to use Scala's dedicated programmers. Even Java programmers who have no Scala experience can perform Code maintenance and use this hybrid development method, modify the existing Java project rather than completely rewrite it. Hope this hybrid development method can help friends who want to use Scala but have no chance at work.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.