我找到了解決方案。相反,使用領域字符串的,我使用的是自定義類像LocalizedText
:
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class LocalizedText {
private String text;
}
系列化,我創建了一個解串器LocalizedTextSerailizer
,這樣的事情:
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
@Component
public class LocalizedTextSerializer extends StdSerializer<LocalizedText> {
private static final long serialVersionUID = 619043384446863988L;
@Autowired
I18nUtil messages;
public LocalizedTextSerializer() {
super(LocalizedText.class);
}
public LocalizedTextSerializer(Class<LocalizedText> t) {
super(t);
}
@Override
public void serialize(LocalizedText value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeString(messages.get(value.getText()));
}
}
I18nUtil
:
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class I18nUtil {
@Autowired
private MessageSource messageSource;
public String get(String code) {
try {
MessageSourceAccessor accessor = new MessageSourceAccessor(messageSource, Locale.getDefault());
return accessor.getMessage(code);
} catch (NoSuchMessageException nsme) {
log.info("Message not found in localization: " + code);
return code;
}
}
}
這非常符合目的,我不必搞砸業務邏輯,我可以本地化任何參數的任何響應在應用程序中。
注:
- 這裏I18nUtil,返回相同的代碼,如果它找不到在message.properties的任何消息。
- 在I18nUtil中使用默認語言環境進行演示。