본문 바로가기

Spring/MVC

Formatter

Formatter: 사실상 두가지 인터페이스를 합친 것

 -Printer: 해당 객체를 (Locale 정보를 참고하여) 문자열로 어떻게 출력할 것인가

 -Parser: 어떤 문자열을 (Locale 정보를 참고하여) 객체로 어떻게 변환할 것인가

 *parameterid로 받는다면 formatter는 필요없음 => Spring Data JPA 사용(도메인 클래스 컨버터)

 

Formatter 등록하는 방법(추가하는 방법)

1. WebMvcConfigureraddFormatters(FormatterRegistry) 메소드 정의

public class PersonFormatter implements Formatter<Person> {

    @Override
    public Person parse(String text, Locale locale) throws ParseException {
        Person person = new Person();
        person.setName(text);
        return person;
    }

    @Override
    public String print(Person object, Locale locale) {
        return object.toString();
    }
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new PersonFormatter());
    }
}

 

2. (스프링 부트 사용시에만 가능) 해당 포메터를 빈으로 등록

@Component
public class PersonFormatter implements Formatter<Person> {

    @Override
    public Person parse(String text, Locale locale) throws ParseException {
        Person person = new Person();
        person.setName(text);
        return person;
    }

    @Override
    public String print(Person object, Locale locale) {
        return object.toString();
    }
}

@Configuration
public class WebConfig implements WebMvcConfigurer {
}

@Component 애노테이션으로 PersonFormatter를 빈으로 등록할 수 있다.

 

<Test 코드 작성>

@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
    @Autowired
    MockMvc mockMvc;

    @Test
    public void hello() throws Exception {

근데, 2번으로 하면 웹 테스트에서는 통과하지만 Test코드를 실행하면 오류가 난다.

Why? @WebMvcTest는 슬라이싱 테스트용이기 때문에 웹과 관련된 bean만 등록해줌

현재, Formatter를 그냥 @Component로 지정 => 웹과 관련된 bean이라고 인식 못함(@Controller가 아니기때문에)

그럼 어떻게 하냐? @WebMvcTest 대신에 @SpringBootTest (통합테스트)로 변경

=> 이렇게 하면 @SpringBootApplication이 붙어있는 곳(main) 부터 시작해서 모든 bean들을 다 등록을 해줌.

=> 오류발생(MockMvc가 자동등록 되지 않음) => class 위에 @AutoConfigureMockMvc 를 덧붙이면 해결 됨

'Spring > MVC' 카테고리의 다른 글

Controller 구성(Formatter 응용)  (0) 2023.07.28