SpringBoot中普通类无法注入service的解决方案

先摆出实际问题:本人在项目中写了钩子方法,在service方法中,通过父类方法,调用子类的实现,结果出现,service无法注入问题?

解决方案:既然spring无法完成普通类的依赖注入,那么我们就手动getBean(思路就是手动调用ApplicationContext.getBean() )。

1、我们手动创建工具类ApplicationContextProvider

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

/**
 * spring boot 项目中  普通类中无法注入service问题解决方案,手动getBean
 * @author ellisonpei
 */

@Component
public class ApplicationContextProvider implements ApplicationContextAware {
    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @SuppressWarnings("static-access")
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过name获取 Bean对象.
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean对象.
     * @param clazz
     * @param 
     * @return
     */
    public static  T getBean(Class clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean对象
     * @param name
     * @param clazz
     * @param 
     * @return
     */
    public static  T getBean(String name, Class clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}

2、父类不用做什么修改

/**
 * 抽象父类
 * 父类通过钩子方法调用子类中的方法
 * @author ellisonpei
 * @param 
 *
 */
public abstract class SelectDataForm {

    //按照年、季度、月份筛选数据
    public abstract List selectedForm(T y);
}

3、在子类中修改调用

/**
 * 按月份计算
 * @author ellisonpei
 */
public class SelectFormByMonth extends SelectDataForm {

    private IIpdrpmgFrptFormService ipdrpmgFrptFormService;

    @Override
    public List selectedForm(IpdrpmgFrptForm ipdrpmgFrptForm) {
      //通过我们自定义封装的 ApplicationContextProvider 来主动getBean
        ipdrpmgFrptFormService = ApplicationContextProvider.getBean(IIpdrpmgFrptFormService.class);
        return ipdrpmgFrptFormService.selectFormByMonth(ipdrpmgFrptForm);
    }
}

修改完毕。ipdrpmgFrptFormService此时再调用就不是null了。

你可能感兴趣的:(SpringBoot中普通类无法注入service的解决方案)