Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Spring Boot Tutorial

1. Create a Spring Project

Goto start.spring.io and choose:

  • maven
  • add dependencies:
      • web
      • data-jpa
      • h2

2. Project Structure

Your project structure will look similar to a typical Java project but will include Scala source files:

scala-java-spring
|-- src
    |-- main
        |-- scala
            |-- controllers
               |-- TodoController.scala
            |-- model
               |-- Todo.scala   
            |-- repository
               |-- TodoRepository.scala   
        |-- resources
            |-- application.properties 
    |-- test
        |-- scala
            |-- Your Scala test files here
|-- pom.xml

3. Update the pom.xml

You need to add dependencies and plugins to your pom.xml for Scala, Spring Boot, and to integrate Scala with Maven. Below is a simplified example of what the pom.xml might include:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>21</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala3-library_3</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <version>4.8.1</version>
                <executions>
                    <execution>
                        <id>scala-compile-first</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>add-source</goal>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>scala-test-compile</id>
                        <phase>process-test-resources</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

4. Write Your Scala Application

Inside the src/main/scala directory, create your Scala application. For example, a simple Spring Boot application in Scala might look like this:

package com.example.demo

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
class DemoApplication

object DemoApplication extends App: 
  SpringApplication.run(classOf[DemoApplication])
  

5. Todo class

package com.example.demo.model

import jakarta.persistence.{Entity, GeneratedValue, GenerationType, Id}

import scala.annotation.meta.companionObject
import scala.beans.BeanProperty

@Entity
class Todo:
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @BeanProperty
  var id: Long = _

  @BeanProperty
  var task: String = _
  

6. Todo Repository

package com.example.demo.repository

import com.example.demo.model.Todo
import org.springframework.data.jpa.repository.JpaRepository

trait TodoRepository extends JpaRepository[Todo, Long]

7. Todo Controller

package com.example.demo.controllers

import com.example.demo.model.Todo
import com.example.demo.repository.TodoRepository
import org.springframework.web.bind.annotation.{GetMapping, PostMapping, RequestBody, RequestMapping, RestController}

import scala.jdk.CollectionConverters.*

@RequestMapping(path= Array("/todo"))
@RestController
class TodoController(todoRepository: TodoRepository):

  @PostMapping
  def save(@RequestBody todo : Todo): Todo = 
    todoRepository.save(todo)
  
  import java.util
  @GetMapping
  def findAll(): util.List[Todo] = 
    todoRepository.findAll()
  

8. Running Your Application

You can run your Scala-Spring Boot application using Maven commands such as mvn spring-boot:run or by running the main method directly from your IDE.

9. Integratie with Java

|-- src
    |-- main
        |-- java
            |-- OtherController.java
package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OtherController {

  @GetMapping("/hello")
  String sayHello() {
    return "hello";
  }
}

And it just works!
So you can integrate Java and Scala easily.
For example by writing your tests in Scala.

10. RestClient

Add a companion object to the Todo class
So we have a decent constructor


@companionObject
object Todo: 
  def apply(task: String): Todo = 
    val todo = new Todo()
    todo.task = task
    todo
    
package com.example.demo

import com.example.demo.model.Todo
import org.springframework.http.MediaType
import org.springframework.web.client.RestClient


@main
def main(): Unit = 

  val todo = Todo("driving")  // call the companion object
  val uriBase = "http://localhost:8080"

  val response: Todo =
    RestClient.create
      .post
      .uri(uriBase + "/todo")
      .contentType(MediaType.APPLICATION_JSON)
      .body(todo)
      .retrieve
      .body(classOf[Todo])

  println(response.task)
  

You could put it in: src --> test --> scala --> TodoRestClient.scala