How to include JPA converter from an external library into a Spring boot project?

Viewed 141

I would like to put in my maven library an Email class used in several Spring boot projects. So I have gather in my lib:

class Email(val value: String)

@JsonComponent
class EmailSerializer : JsonSerializer<Email>()

@JsonComponent
class EmailDeserializer : JsonDeserializer<Email>()

@Converter(autoApply = true)
class EmailConverter : AttributeConverter<Email, String>

@Configuration
@Import(value = [EmailSerializer::class, EmailDeserializer::class, EmailConverter::class])
class EmailConfiguration

In my project then I can include them all at once:

@Configuration
@Import(value = [EmailConfiguration::class])
class ApplicationConfiguration

Since, the JsonComponents are well imported, but I have failed to configure correctly my spring project in order to auto apply the EmailConverter. I still have to apply it explicitely:

@Entity
@Table(name = "user")
class User(
    @Convert(converter = EmailConverter::class)
    var email: Email,
)

else I get this error: org.hibernate.MappingException: Could not determine type for: com.betomorrow.commons.components.Email, at table: user, for columns: [org.hibernate.mapping.Column(email)]

Since @Converter does not make the class a Component, I tried to add @Component and @Configurable and also without the EmailConfiguration class but with a ComponentScan("myPackage"), but still the same.

Any idea ? Thank you.

1 Answers

You need to register the converter as a Spring bean like so (in class annotated with @Configuration:

@Bean 
public MyConverter myconverter() {
  return new MyConverter();
}
Related