만들어야 하는 package 및 클래스

Song(model)

package kr.ac.kumoh.s20210353.w24w05thymeleaf.model

data class Song(
    var id: Int,
    var title: String,
    var singer: String,
)

SongRepository(repository)

package kr.ac.kumoh.s20210353.w24w05thymeleaf.repository

import kr.ac.kumoh.s20210353.w24w05thymeleaf.model.Song
import org.springframework.stereotype.Repository

@Repository

class SongRepository {
    protected val songs = listOf(
        Song(1, "일레븐", "아이브"),
        Song(2, "눈의꽃", "박효신"),
        Song(3, "사랑에 연습이 있었다면", "임재현"),
    )

    val songsSize: Int
        get() = songs.size

    fun getSong(index: Int) = songs[index]

    fun fetchSong() = songs
}

SongService(service)

package kr.ac.kumoh.s20210353.w24w05thymeleaf.service

import kr.ac.kumoh.s20210353.w24w05thymeleaf.repository.SongRepository
import org.springframework.stereotype.Service
import kotlin.random.Random

@Service
class SongService(val repository: SongRepository)
{
    fun getRandomSong() = repository.getSong(Random.nextInt(repository.songsSize))
    fun getAllSongs() = repository.fetchSong()
}

SongController(controller)

package kr.ac.kumoh.s20210353.w24w05thymeleaf.controller

import kr.ac.kumoh.s20210353.w24w05thymeleaf.service.SongService
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping

@Controller
class SongController(val service: SongService)
{
    @GetMapping("/song/random")
    fun getRandomSong(model: Model): String
    {
        model.addAttribute("song", service.getRandomSong()) //이렇게 주면 json 형식으로 나옴
        //model.addAttribute("singer", service.getRandomSong().singer)
        //model.addAttribute("id", service.getRandomSong().id)
        return "random"
    }
}

random.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf</title>
</head>
<body>
    <h2>추천 노래</h2>
    <p>제목 : [[${song.title}]]</p>
    <p>가수 : [[${song.singer}]]</p>
    <p>순서 : [[${song.id}]]</p>

</body>
</html>

클래스 만드는 순서