Spring – wpisy w temacie

Spring custom validator from interface

When we use layers separation it sometimes become problematic to use custom validator annotation, as to execute it we need service layer not available in data layer. After some digging around I have found a solution, to set validatedBy annotation paramter to interface class instead of implementation class and handle that in the service layer with customized validator factory code.

Adding custom Converters to ConversionService in Spring MVC

If somebody starts to play a little with a Sping MVC application sooner rather than later will see a message saying something like

(...) nested exception is java.lang.IllegalArgumentException: 
Cannot convert value of type [java.lang.String] to required type [sth.model.MyCustomType] for property 'propertyName': no matching editors or conversion strategy found

There are a lot of spnippets around how to create a converter, name it StringToMyCustomTypeConverter (I can recommend this one: http://www.javabeat.net/2011/02/introduction-to-spring-converters-and-formatters/), and also how to add it in the xml configuration:

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
  <property name="converters">
      <bean id="StringToMyCustomTypeConverter" class="sth.converter.StringToMyCustomTypeConverter" />

In my spring familiarization project I've decided to use java config to some extend. So I spent time looking around how to add custom converters in code. I easly run into problem with two ConversionService(s) registerd which ended with no explicit bean with name 'conversionService' error. Finally I found working (and very easy indeed) solution. My configuration class e.g. AppConfig (annotated with @Configuration), has to extend WebMvcConfigurerAdapter (or implement WebMvcConfigurer interface) and just override addFormatters method (you can register converters there also):

public void addFormatters(FormatterRegistry formatterRegistry) {
    formatterRegistry.addConverter(new StringToMyCustomTypeConverter());