通过反射调用的类中使用Spring@Autowired自动装配的成员为空的解决办法不依赖servlet context获取Spring Application Contexts

//反欺诈接口地址
if(null ==iSystemPublicDictionaryService) {
    iSystemPublicDictionaryService =  SpringContextUtil.getBean("ISystemPublicDictionaryService",SystemPublicDictionaryServiceImpl.class);
}
String url = iSystemPublicDictionaryService.getDictionaryValueByTypeAndKey(SystemPublicDictionaryRmsKeyConstants.SystemConstant,SystemPublicDictionaryRmsKeyConstants.VALID_PHONE_BLACSpringContextUtilK);
SpringContextUtil 类代码:
 
  
package com.jzfq.rms.autoApprove.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


/**
 * 说明 不依赖servlet context获取Spring Application Contexts
 */

public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext contex) throws BeansException {
        SpringContextUtil.context = contex;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static <T> T getBean(String beanId, Class<T> c) {
        return (T) context.getBean(beanId, c);
    }

    /**
     * 获取对象
     * @param 
     * @return T
     * @throws BeansException
     */
    public static <T> T getBean(Class<T> requiredType) throws BeansException {
        return context.getBean(requiredType);
    }
}

<bean id="springContextUtil" class="com.jzfq.rms.monitor.utils.SpringContextUtil">bean>

 
  
 
  

你可能感兴趣的:(java后端,spring)