spring不支持静态变量的注入解决方案

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }

}

以上是关于spring不支持静态变量的注入解决方案的主要内容,如果未能解决你的问题,请参考以下文章

在静态工具类中注入Service的解决方案

踩坑:Spring静态变量/构造函数注入失败(注入为null)问题的解决方案

踩坑:Spring静态变量/构造函数注入失败(注入为null)问题的解决方案

SpringBoot @Autowired中注入静态方法或者静态变量

spring 给静态变量注入值

Spring不能直接@autowired注入Static变量问题和解决方案