0

I am using the Hibernate validation mechanism in my Micronaut project as the documentation suggests.

Unfortunately, I need to react to validation errors manually and handle the errors with specific exceptions. Thus, I can not use the recommended way of validating method arguments

fun doStuff(@Valid argument: MyArgument): ... {...}

I want to inject the Validator to my class, call it and process the results myself. In Spring this was easily doable. Micronaut unfortunately tells me it does not know how to provide a validator:

Message: No bean of type [javax.validation.Validator] exists

My class looks like this

import javax.validation.Validator

@Controller
class MyController(val validator: Validator) {...}

Am I missing something? I read somewhere that there should be a default validation bean factory available as I am using Micronaut v1.1.0.

Thanks.

Florian Hansen
  • 746
  • 7
  • 19

2 Answers2

1

You can inject a javax.validation.ValidatorFactory that will delegate to whatever implementation you have on the classpath.

Starting in 1.2.0 (not released yet), you will be able to inject a io.micronaut.validation.validator.Validator that is Micronaut's implementation of validation that doesn't use reflection.

James Kleeh
  • 12,094
  • 5
  • 34
  • 61
0

One can provide the validator by adding a Factory that provides the Validation bean like this:

@Factory
class ValidatorFactory {
    @Singleton
    fun validator(): Validator = Validation.buildDefaultValidatorFactory().validator
}

This adds the necessary Validator bean to the application context and makes it available.

Florian Hansen
  • 746
  • 7
  • 19