TIL - 21.02.02
less than 1 minute read
[SPRING] 메세지 처리
- MessageUtils : 일관된 메세지 처리를 위해 구현
import org.springframework.context.support.MessageSourceAccessor;
import static com.google.common.base.Preconditions.checkState;
public class MessageUtils {
private static MessageSourceAccessor messageSourceAccessor;
public static String getMessage(String key) {
checkState(null != messageSourceAccessor, "MessageSourceAccessor is not initialized.");
return messageSourceAccessor.getMessage(key);
}
public static String getMessage(String key, Object... params) {
checkState(null != messageSourceAccessor, "MessageSourceAccessor is not initialized.");
return messageSourceAccessor.getMessage(key, params);
}
public static void setMessageSourceAccessor(MessageSourceAccessor messageSourceAccessor) {
MessageUtils.messageSourceAccessor = messageSourceAccessor;
}
}
- messages.properties : 문자열 하드코딩하지 않고 property 사용
error.auth=AuthenticationFailed
error.auth.details=Authentication error (cause: {0})
import com.github.prgrms.social.util.MessageUtils;
public class UnauthorizedException extends ServiceRuntimeException {
public static final String MESSAGE_KEY = "error.auth";
public static final String MESSAGE_DETAIL = "error.auth.details";
public UnauthorizedException(String message) {
super(MESSAGE_KEY, MESSAGE_DETAIL, new Object[]{message});
}
@Override
public String getMessage() {
return MessageUtils.getMessage(getDetailKey(), getParams());
}
@Override
public String toString() {
return MessageUtils.getMessage(getMessageKey());
}
}
REF