π νμ λ³ν: Converter & Formatter
Converter
- νμ κ° λ¨λ°©ν₯ λ³νκΈ° (Object β Object)
- μ: λ¬Έμμ΄(String)μ Enum νμ μΌλ‘ λ³ν
Converter<S, T>
μΈν°νμ΄μ€λ₯Ό ꡬννμ¬ μ¬μ©- ex. Enum λ³ν λ±μ μ¬μ©
@Component
public class StringToRoleConverter implements Converter<String, Role> {
@Override
public Role convert(String source) {
return Role.valueOf(source.toUpperCase());
}
}
μ μ© λ°©λ²
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToRoleConverter());
}
}
Formatter
- λ¬Έμμ΄ β> κ°μ²΄ κ° μλ°©ν₯ λ³νμ μ§μ
- μ£Όλ‘ λ μ§, μ«μ, νν λ±μ μ¬μ©μ μΉνμ ν¬λ§· μ²λ¦¬μ μ¬μ©
Formatter<T>
μΈν°νμ΄μ€ ꡬν
@Component
public class LocalDateFormatter implements Formatter<LocalDate> {
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
@Override
public LocalDate parse(String text, Locale locale) {
return LocalDate.parse(text, formatter);
}
@Override
public String print(LocalDate object, Locale locale) {
return object.format(formatter);
}
}
β Formatterλ
WebMvcConfigurer.addFormatters()
λ₯Ό ν΅ν΄ λ±λ‘ν΄μΌ μ μ©λ¨