javaspring-bootkotlinautowiredkotlin-lateinit

xception in thread "Thread-6" kotlin.UninitializedPropertyAccessException: lateinit property has not been initialized


Hi guys I am developing an application with Spring Boot, Although I am having some problems initializing a JPA repository in a thread generating the following error

Exception in thread "Thread-6" kotlin.UninitializedPropertyAccessException: lateinit property contactTypeAudioPathRepository has not been initialized
    at com.sopristec.sa_tas.controllers.ProvisioningController$createAudioWithAsync$executeP$1.run(ProvisioningController.kt:96)
    at java.lang.Thread.run(Thread.java:748)

I'm using @Autowired to start it and this is what the function looks like

@Autowired
private  lateinit var contactTypeAudioPathRepository: ContactTypeAudioPathRepository


fun createAudioWithAsync(menuChoice: String, presentation: String) {

        val executeP = Thread{
            val message = "Press $menuChoice to save this phone number as $presentation. Or " +
                    "Press 9 to save as work number"


            val commandVoice = mutableListOf<String>("python","pythonScript/main.py",message);

            val buildAudio = ProcessBuilder(commandVoice).start()

            val getPath = buildAudio.inputStream.bufferedReader().use { it.readText() }

            if(getPath.isEmpty()){
                println("A python script failed")
            }
            println(getPath.replace("\n","").replace("att_sas_pyttsx3/",""))

            val fileName = getPath.replace("\n","")
            contactTypeAudioPathRepository.save(ContactTypeAudioPath(0,fileName))

           // Genera error --> contactTypeAudioPathRepository.add("mediaLink").subscribe()


        }.start()
//        executeP.start();
        //contactTypeAudioPathRepository.add("mediaLink").subscribe()

    }

This is the repository, as you can see is with JPA's CrudRepository

@Repository
interface ContactTypeAudioPathRepository : CrudRepository<ContactTypeAudioPath,Int> {

}

Thanks


Solution

  • You don't need to use lateinit to Autowire your Repository

    Spring allows you to use Constructor Injection

    @Component
    class ProvisioningController(private val repository:ContactTypeAudioPathRepository) {
    
       fun createAudioWithAsync(menuChoice: String, presentation: String) {
           ....
       }
    }