先摆出实际问题:本人在项目中写了钩子方法,在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;
@Component public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@SuppressWarnings("static-access") @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; }
public static ApplicationContext getApplicationContext() { return applicationContext; }
public static Object getBean(String name) { return getApplicationContext().getBean(name); }
public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); }
public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); }
}
|
2、父类不用做什么修改
public abstract class SelectDataForm<T> {
public abstract List<T> selectedForm(T y); }
|
3、在子类中修改调用
public class SelectFormByMonth extends SelectDataForm<IpdrpmgFrptForm> {
private IIpdrpmgFrptFormService ipdrpmgFrptFormService;
@Override public List<IpdrpmgFrptForm> selectedForm(IpdrpmgFrptForm ipdrpmgFrptForm) { ipdrpmgFrptFormService = ApplicationContextProvider.getBean(IIpdrpmgFrptFormService.class); return ipdrpmgFrptFormService.selectFormByMonth(ipdrpmgFrptForm); } }
|