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);
}
}
OutputJoe, IT, 123-456-7890 Employee{name='Joe', dept='IT', phoneNumber='123-456-7890'}
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 3.2.3.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|