Consider defining a bean of type repository in your configuration. Kotlin spring boot

Viewed 268

I'm trying to build and run spring boot app using kotlin language. I researched some similar questions but could not make my app build. Error output: Parameter 0 of constructor in com.github.raketa92.mailservice.service.EmailService required a bean of type 'com.github.raketa92.mailservice.repository.MailRepository' that could not be found. Consider defining a bean of type 'com.github.raketa92.mailservice.repository.MailRepository' in your configuration. I found github repository where this kind of code builds and runs successfully.

Here is my repository file:

interface MailRepository : CoroutineCrudRepository<Email, Long>{
@Query("SELECT * FROM email WHERE messageId = :messageId")
suspend fun getEmailByMessageId(messageId: Int): Email?

@Query("UPDATE email set statusId = :statusId where id = :id")
suspend fun updateStatus(statusId: Int, id: Long): Email
}

Here is my Service file:

package com.github.raketa92.mailservice.service

import com.github.raketa92.mailservice.model.Email
import com.github.raketa92.mailservice.repository.MailRepository
import kotlinx.coroutines.flow.Flow
import org.springframework.mail.SimpleMailMessage
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.stereotype.Service

@Service
class EmailService(
    private val  mailRepository: MailRepository,
    private val javaMailSender: JavaMailSender
    ) 
{
fun sendMail(email: Email) {
    val message = SimpleMailMessage()
    message.setSubject(email.subject)
    message.setText(email.message!!)
    message.setTo(email.to)
    message.setFrom("test@mail.com")
    javaMailSender.send(message)
    println("email sent")
}

suspend fun getAllEmails(): Flow<Email> = mailRepository.findAll()

suspend fun getEmailById(id: Long): Email? = mailRepository.findById(id)

suspend fun getEmailByMessageId(messageId: Int): Email? = mailRepository.getEmailByMessageId(messageId)

suspend fun createEmail(email: Email): Email = mailRepository.save(email)

suspend fun updateStatus(statusId: Int, id: Long): Email = mailRepository.updateStatus(statusId, id)
}
1 Answers

Your EmailService is a Spring @Service, so Spring will create an instance of it at start-up.

But its constructor needs a MailRepository instance.  And you haven't told it where to get one from, so it throws the runtime error you've seen.

The usual way to tell Spring about a repository interface is to annotate it as @Repository; Spring then knows to create an instance (of a synthetic subclass implementing) that interface.

Related