Home > Software Development > Spring: Auto Detecting Type Converters

Spring: Auto Detecting Type Converters

So, you have been enjoying Spring’s type converter system. However, like me, you are lazy and do not want to register all of your type converters manually. Using JavaConfig, is trivial to have the container autodetect and register type converters for you.

First, annotate your type converters with @Component. This will make them Spring-managed beans.

Next, add the following code to your JavaConfig:

@Configuration
@EnableWebMvc
public class MVCConfig extends WebMvcConfigurationSupport {
	@Inject
	private List<Formatter<?>> formatters;

	@Override
	public void addFormatters(FormatterRegistry registry) {
		for (Formatter<?> formatter : formatters)
			registry.addFormatter(formatter);
	}

}

During container set up, Spring will inject a list of all managed converters. All you have to do is iterate over the list and add each one to the formatter registry.

Categories: Software Development Tags:
  1. No comments yet.