본문 바로가기
Java & Kotlin/Spring

[Spring] UnmarshallingFailureException 에러 해결하기

by heekng 2022. 6. 6.
반응형

UnmarshallingFailureException 에러 해결하기

Spring Batch 에서 StaxEventItemReader 사용 중 xml 파일을 읽어 객체에 매핑하는 과정에 Staorg.springframework.oxm.UnmarshallingFailureException가 발생했다.

org.springframework.oxm.UnmarshallingFailureException: XStream unmarshalling exception; nested exception is com.thoughtworks.xstream.security.ForbiddenClassException: com.heekng.springbatch.Customer

에러가 발생한 이유

oxmxstream를 사용하기 위해 org.springframework:spring-oxmcom.thoughtworks.xstream:xstream의존성 최신버전을 추가하였다.

이는 Stax API 방식으로 데이터를 읽기 위해 사용한 라이브러리인데, XStream에서 보안 프레임워크를 구성하지 않았기 때문에 생긴 에러였다.

해결 방법

1번

추가적인 설정을 하지 않고 해결하는 방법은 라이브러리 버전을 낮추는 것이다.

공식적으로 xtream 1.4.18버전부터 해당 보안 프레임워크 구성에 대해 강제성을 띄고 있다.

implementation 'org.springframework:spring-oxm:5.3.7'
implementation 'com.thoughtworks.xstream:xstream:1.4.16'

이 방법을 추천하지 않는 이유는

Security framework of XStream not explicitly initialized, using predefined black list on your own risk.
//사전 정의된 블랙리스트를 사용하여 XStream의 보안 프레임워크가 명시적으로 초기화되지 않았습니다.

위와 같은 경고가 발생하기 때문이다.

2번

스택오버플로우에서 간단하게 해결하는 방법을 찾을 수 있었다.

1번에서 생기는 경고 때문에 최신 버전을 사용하며, 보안 프레임워크를 구성하는 방법으로 해결해보자.

XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();
xStreamMarshaller.setAliases(aliases);
XStream xStream = xStreamMarshaller.getXStream();

//첫 번째 방법
xStream.allowTypesByWildcard(new String[]{
        "com.heekng.springbatch.**"
});

//두 번째 방법
xStream.allowTypes(new Class[] {
        Customer.class
});

위와 같이 XStreamMarshaller 객체에서 XStream을 받아와 XStream에 허용할 클래스를 지정해준다.

첫 번째 방법의 경우 String 배열로 패키지 단위로 허용하고, 두 번째 방법의 경우 클래스 배열을 이용해 클래스 단위로 허용할 수 있다.

반응형