1. 程式人生 > >spring mvc中,如何在 Java 代碼裏,獲取 國際化 內容

spring mvc中,如何在 Java 代碼裏,獲取 國際化 內容

source 所在 bundle 註入 pre 定義 pan col void

首先,在Spring的application.xml中定義

 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <!-- 國際化信息所在的文件名 -->
        <property name="basename" value="messages/messages"/>
        <!-- 如果在國際化資源文件中找不到對應代碼的信息,就用這個代碼作為名稱  -->
        <
property name="useCodeAsDefaultMessage" value="true"/> </bean>

其中,id 的值必須是 “messageSource”,否則會報錯

首先,我想到的是,既然它是一個被聲明好的bean,那麽,應該可以使用 @Autowired 標簽來綁定吧。於是我寫了如下的代碼:

public class Const {  
    @Autowired  
    private static ResourceBundleMessageSource rms  
      
    public static String getTextValue(String key) {  
        
return rms.getMessage(key, null, null); } }

rms 的值一直是null,也就是說註入失敗了

後來在網上查到,“ApplicationContext” 這個接口繼承了“MessageSource”接口,那麽我們只要獲取項目的 ApplicationContext 的實現類,就可以通過 getMessage() 方法來獲取國際化文件內容了。

那麽要如何簡單方便的來獲取 ApplicationContext 的實現類呢?這個時候就需要另一個接口了,即“ApplicationContextAware”,任何類實現這個接口,均會被註入 ApplicationContext 。

public class SpringUtil implements ApplicationContextAware {  
    private static ApplicationContext applicationContext;  
  
    public static ApplicationContext getApplicationContext() {  
        return applicationContext;  
    }  
  
    @Override  
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {  
        applicationContext = arg0;  
    }  
  
    public static Object getBean(String id) {  
        Object object = null;  
        object = applicationContext.getBean(id);  
        return object;  
    }  
} 

當然,必須要將上面的 SpringUtil 類在application.xml文件中配置一下,才能讓它被spring框架讀取,然後給它註入 ApplicationContext。配置很簡單:

<bean id="SpringUtil" class="util.SpringUtil"/>  

這樣就行了

public class Const {  
      
    public static String getTextValue(String key) {  
        return SpringUtil.getApplicationContext().getMessage(key, null, null);  
    }  
}  

spring mvc中,如何在 Java 代碼裏,獲取 國際化 內容