@Autowired service does not work on Constraintvalidator in Kotlin

Asked

Viewed 106 times

-1

I’ve been using Spring Boot for some time in Java and never had a problem with injections using @Autowired. But recently I decided to transform a Rest API project that was in Java to Kotlin, all the code worked perfectly less my Constraintvalidators that I use to validate the incoming fields.

Follow the code at Kotlin:

@Constraint(validatedBy = [CargoInsertValidator::class])
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
annotation class CargoInsert(
        val message: String = "Erro de validação",
        val groups: Array<KClass<*>> = [],
        val payload: Array<KClass<out Payload>> = []
)

class CargoInsertValidator : ConstraintValidator<CargoInsert, Cargo> {

    @Autowired
    lateinit var cargoService: CargoService

    override fun initialize(constraintAnnotation: CargoInsert) {}

    override fun isValid(objDTO: Cargo, context: ConstraintValidatorContext): Boolean {
        // mais código
        val cargoNome: Cargo = cargoService.findByNome(objDTO.nome)
        // mais código
    }
}

When you get to the line where I call a "cargoService" function I get the following error:

ConstraintViolationImpl{interpolatedMessage='lateinit property cargoService has not been initialized'

As you can see, spring doesn’t boot cargoService so I can use it. But this only happens in this class (which extends Constraintvalidator), because in any other part of the project where I inject the cargoService it works perfectly. Remembering that similar code in Java works smoothly. I’ve tried annotating Cargoinsertvalidator with @Component, @Service, @Configuration and nothing.

Another detail, the error only occurs when I try to insert into the post table during spring startup, whether it is done via Commandlinerunner or creating a @Bean, which happens in the "test" profile when I want to start the database from scratch and insert some dummy data. But if I don’t try to insert anything at the beginning and leave to insert later using the Rest API itself it works. That is, at some point this injection by @Autowired is ready, but not when I need it at the beginning, which in Java did not seem to be a problem.

Does anyone have any idea what’s going on? Why isn’t the injection done in Kotlin?

1 answer

-1

After much searching I found the solution in this answer:

https://stackoverflow.com/a/53897856/13098285

Putting my database startup in the Starthere class all @Autowired were already ready to be used.

Thank you so much @Adrenal1ne

Browser other questions tagged

You are not signed in. Login or sign up in order to post.