2017-06-12 21 views
1

我想本地化我的項目中每個API的響應幾乎每個參數。春季啓動本地化來自RestController的每個響應參數

我已經想通了,我們可以做這樣的事情在春季啓動:

,並保持代碼與本地化的消息映射messages_en.propertiesmessages_fr.properties

但我的應用程序專有兩個要求:

  • 我想分開這個邏輯從我的業務邏輯,即我不想寫每個本地化邏輯和每個控制器。
  • 我想嘗試通過服務器的所有響應的每個響應參數,也許Jackson正在將對象轉換爲字符串或轉換爲JSON後。

有沒有辦法在春季啓動來實現這一點,或者有沒有任何圖書館可用於此?

回答

0

我找到了解決方案。相反,使用領域字符串的,我使用的是自定義類像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; 
     } 
    } 
} 

這非常符合目的,我不必搞砸業務邏輯,我可以本地化任何參數的任何響應在應用程序中。

注:

  1. 這裏I18nUtil,返回相同的代碼,如果它找不到在message.properties的任何消息。
  2. 在I18nUtil中使用默認語言環境進行演示。