Creating Enterprise Scala Beans: When Scala Meets Java EE

This article demonstrates the integration of Scala with Java EE by implementing Enterprise Java Beans (EJBs) using Scala programming language. Using Apache TomEE 1.5.1 as the application server and Scala 2.10, a simple stateless session bean is created and successfully injected into a Java servlet using CDI. The implementation showcases Scala's excellent Java interoperability features and proves that Enterprise Scala Beans are a viable option for enterprise development.

2 Minutes reading time

Behold the masterpiece that AI hallucinated while reading this post:

"How Little Scala Learned to Play Nice with Big Java EE"

(after I fed it way too many marketing blogs and memes)

Created using DALL-E 3

AI-Generated: How Little Scala Learned to Play Nice with Big Java EE

Once i was thinking about writing Enterprise Java Beans(EJBs) with the Scala programming language. This should be easy as Scala greatly incorporates with existing Java code bases. But let’s create a small test to verify this!

For this example, i am using Apache TomEE 1.5.1 as a JEE Web Profile certified server and Scala 2.10 to create a small stateless session bean and invoke it from a servlet. The stateless bean is injected to the servlet using CDI. I use IntelliJ 12 as my favorite IDE.

Here is the Scala code for the stateless session bean:

package de.mirkosertic.scala

import javax.ejb.Stateless
import util.Random

@Stateless
class StatelessBean {

   val random = Random

   def sayHello() = "Hello " + random.nextInt
}

I use the JEE @Stateless annotation to mark the Scala class as a stateless session bean. The bean has a public sayHello() method, which just returns the string “Hello ” concatenated with a random number. Here is the JEE servlet which uses the JEE bean:

package de.mirkosertic.java;

import de.mirkosertic.scala.StatelessBean;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/servlet")
public class TestServlet extends HttpServlet {

    @EJB
    StatelessBean statelessBean;

    @Override
    protected void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException {
        PrintWriter theWriter = aResponse.getWriter();
        theWriter.print("<html><body>");
        theWriter.print(statelessBean.sayHello());
        theWriter.print("</body></html>");
    }
}

After compiling it and invoking it from the browser, we see a “Hello” text with a random number. It is working! We can create Enterprise Java Beans with Scala, so we have Enterprise Scala Beans :-)

Git revision: 2e692ad