spring不支持靜態變量的注入解決方案

I18N工具類

public class I18N {

    
    private static ApplicationContext ctx = BeanContext.ctx;

    private static ReloadableResourceBundleMessageSource messageSource;

    public static String getMessage(String key, Object... msgParam) {
        if(ctx == null){
            return key;
        }
        if(messageSource != null){
            messageSource.getMessage(key, msgParam, key, Locale.CHINA);
        }
        Map<String, ReloadableResourceBundleMessageSource> map = ctx.getBeansOfType(ReloadableResourceBundleMessageSource.class);
        if(map.size() ==  0){
            return key;
        }
        String beanKey = map.keySet().toArray(new String[]{})[0];
        messageSource = map.get(beanKey);
        return messageSource.getMessage(key, msgParam, key, Locale.CHINA);
    }
}


BeanContext類

public class BeanContext implements ApplicationContextAware {    
    
    public static ApplicationContext ctx;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        BeanContext.ctx = context;
    }
    
    public static Object getBean(String beanName) {
        return ctx.getBean(beanName);
    }
    
    public static <T> T getBean(Class<T> clazz) {
        return ctx.getBean(clazz);
    }
    
    public static <T> Map<String, T> getBeansOfType(Class<T> type) {
        Map<String, T> map = ctx.getBeansOfType(type);
        if (map == null) {
            map = new HashMap<String, T>();
        }
        return map;
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章