简体   繁体   中英

Got lateinit property has not been initialized error when using @Autowired and @Component

This AwsSqsUtil class has a Component annotation, when I want to use it in my main function, I got error "kotlin.UninitializedPropertyAccessException: lateinit property awsSqsUtil has not been initialized, how to fix this issue?

"

@Component
class AwsSqsUtil {
   fun sendMessageToSqs() {
  }
}
@Autowired
private lateinit var awsSqsUtil: AwsSqsUtil

awsSqsUtil.sendMessageToSqs()

Where exactly is your variable declaration? Is it inside a class that is a component/service/controller/etc, or just on top level?

I expect your answer to be top lever or a normal class, since that is when you'd usually encounter this.

And the solution would be to leave the main class alone in a spring boot app. If you want something to run at start-up, you can create a fun (inside a proper spring container) that you annotate with @PostConstruct . This way it will run after the spring app has actually started, and you'll be able to autowire at will.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM