Close

Spring - Custom Formatter

[Last Updated: Apr 23, 2023]

Similar to creating custom converter, we can also create custom formatters, register it with a ConversionService and inject the ConversionService as a bean.

Please also check out another custom formatter example in a MVC application.

Example

package com.logicbig.example;

public class Employee {
  private String name;
  private String dept;
  private String phoneNumber;
    .............
}

The custom formatter

The following custom formatter will convert employee string (<name>, <dept>, <phoneNumber>) to Employee object and vice versa.

package com.logicbig.example;

import org.springframework.format.Formatter;
import java.text.ParseException;
import java.util.Locale;
import java.util.StringJoiner;

public class EmployeeFormatter implements Formatter<Employee> {

  @Override
  public Employee parse(String text,
                        Locale locale) throws ParseException {

      String[] split = text.split(",");
      if (split.length != 3) {
          throw new ParseException("The Employee string format " +
                  "should be in this format: Mike, Account, 111-111-1111",
                  split.length);
      }
      Employee employee = new Employee(split[0].trim(),
              split[1].trim(), split[2].trim());
      return employee;
  }

  @Override
  public String print(Employee employee, Locale locale) {
      return new StringJoiner(", ")
              .add(employee.getName())
              .add(employee.getDept())
              .add(employee.getPhoneNumber())
              .toString();

  }
}

Main class

package com.logicbig.example;

import org.springframework.format.support.DefaultFormattingConversionService;

public class CustomFormatterExample {

  public static void main(String[] args) {
      DefaultFormattingConversionService service =
              new DefaultFormattingConversionService();
      service.addFormatter(new EmployeeFormatter());

      Employee employee = new Employee("Joe", "IT", "123-456-7890");
      String string = service.convert(employee, String.class);
      System.out.println(string);

      //converting back to Employee
      Employee e = service.convert(string, Employee.class);
      System.out.println(e);
  }
}

Output

Joe, IT, 123-456-7890
Employee{name='Joe', dept='IT', phoneNumber='123-456-7890'}

Example Project

Dependencies and Technologies Used:

  • spring-context 4.3.4.RELEASE (Spring Context)
  • JDK 1.8
  • Maven 3.8.1

Spring Custom Formatter Example Select All Download
  • spring-custom-formatting
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • EmployeeFormatter.java

    See Also