Data Binding

์‚ฌ์šฉ์ž๋‚˜ ์™ธ๋ถ€ ์„œ๋ฒ„์˜ ์š”์ฒญ ๋ฐ์ดํ„ฐ๋ฅผ ํŠน์ • ๋„๋ฉ”์ธ ๊ฐ์ฒด์— ์ €์žฅํ•ด์„œ Request ์— ๋‹ด์•„์ฃผ๋Š” ๊ฒƒ์„ ๋œปํ•œ๋‹ค.

Converter<S, T> Interface

package org.springframework.core.convert.converter;

public interface Converter<S, T> {

    T convert(S source);
}

S(Source) ํƒ€์ž…์„ ๋ฐ›์•„ T(Target) ํƒ€์ž…์œผ๋กœ ๋ณ€ํ™˜ํ•ด์ฃผ๋Š” Interface

  • ํ™œ์šฉ ๋ฐฉ๋ฒ•

// ์š”์ฒญ
GET /user-info
x-auth-user : {"id":123, "name":"Paul"}

// ์œ ์ € ๊ฐ์ฒด
public class XAuthUser {
    private int id;
    private String name;

    // the usual getters and setters...
}

@GetMapping("/user-info")
public UserInfoResponse getUserInfo(
	@RequestHeader("x-auth-user") XAuthUser xAuthUser){

	// get User Info logic here...
}
@Component
public class XAuthUserConverter implements Converter<String, XAuthUser> {
	@Override
	public XAuthUser convert(String source) {
		return objectMapper.readValue(source, XAuthUser.class);
	}
}

ํ—ค๋”์— ๋‹ด๊ธด json ํ˜•์‹ ๋ฌธ์ž์—ด์„ XAuthUser์— ๋ฐ”๋กœ ๋‹ด๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ Converter ๋ฅผ Bean ์œผ๋กœ ๋“ฑ๋กํ•  ์ˆ˜ ์žˆ๋‹ค..

์ด์™€ ๋น„์Šทํ•˜๊ฒŒ PathParameter ๋‚˜ ๊ธฐํƒ€ ํŠน์ˆ˜ํ•œ ๊ฒฝ์šฐ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ํŠน์ • ๊ฐ์ฒด์— ๋‹ด๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ

  • Converter ๋ฅผ ๋งŒ๋“ค์–ด์„œ Spring ์— Bean ์œผ๋กœ ๋“ฑ๋ก

  • ์Šคํ”„๋ง ๋‚ด์— ConversionService ๋ผ๋Š” ๋‚ด์žฅ๋œ ์„œ๋น„์Šค์—์„œ Converter ๊ตฌํ˜„์ฒด Bean ๋“ค์„ Converter ๋ฆฌ์ŠคํŠธ์— ๋“ฑ๋ก

  • ์™ธ๋ถ€๋ฐ์ดํ„ฐ๊ฐ€ ๋“ค์–ด์˜ค๊ณ , Source Class Type โ†’ Target Class Type ์ด Converter ์— ๋“ฑ๋ก๋œ ํ˜•์‹๊ณผ ์ผ์น˜ํ•˜๋ฉด ํ•ด๋‹น Converter ๊ฐ€ ๋™์ž‘ํ•˜๋Š” ์›๋ฆฌ

Formatter

ํŠน์ • ๊ฐ์ฒด โ†” String ๊ฐ„์˜ ๋ณ€ํ™˜์„ ๋‹ด๋‹น

  • Date โ†” String ๊ฐ„์˜ ๋ณ€ํ™˜์„ ์ˆ˜ํ–‰ํ•˜๋Š” Formatter

package org.springframework.format.datetime;

public final class DateFormatter implements Formatter<Date> {
    public String print(Date date, Locale locale) {
        return getDateFormat(locale).format(date);
    }

    public Date parse(String formatted, Locale locale) throws ParseException {
        return getDateFormat(locale).parse(formatted);
    }
		// getDateFormat ๋“ฑ ์ผ๋ถ€ ๊ตฌํ˜„์€ ํ•ต์‹ฌ์— ์ง‘์ค‘ํ•˜๊ธฐ ์œ„ํ•ด ์ƒ๋žต... 
}
  • print API ์š”์ฒญ์— ๋Œ€ํ•œ ์‘๋‹ต์„ ์ค„ ๋•Œ, Date ํ˜•์‹์œผ๋กœ ๋œ ๋ฐ์ดํ„ฐ๋ฅผ ํŠน์ • locale ์— ๋งž์ถ˜ String ์œผ๋กœ ๋ณ€ํ™˜

  • parse API ์š”์ฒญ์„ ๋ฐ›์•„์˜ฌ ๋•Œ, String ์œผ๋กœ ๋œ "2021-01-01 13:15:00" ๊ฐ™์€ ๋‚ ์งœ ํ˜•์‹์˜ ๋ฐ์ดํ„ฐ๋ฅผ Date ๋กœ ๋ณ€ํ™˜ํ•˜๋„๋ก ํ•จ

Formatter ๋„ Converter ์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ Spring Bean ์œผ๋กœ ๋“ฑ๋กํ•˜๋ฉด ์ž๋™์œผ๋กœ ConversionService ์— ๋“ฑ๋ก์‹œ์ผœ์ฃผ๊ธฐ ๋•Œ๋ฌธ์— ํ•„์š”์— ๋”ฐ๋ผ ์ž๋™์œผ๋กœ ๋™์ž‘ํ•˜๊ฒŒ ๋œ๋‹ค. (์š”์ฒญ/์‘๋‹ต ์‹œ ํ•ด๋‹น ๋ฐ์ดํ„ฐ ํƒ€์ž…์ด ์žˆ๋Š” ๊ฒฝ์šฐ)

Last updated