SpringBoot定时任务 Service层无法注入问题
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ApplicationContextUtil.applicationContext = applicationContext; } public static Object getBean(String beanName) { return applicationContext.getBean(beanName); } }
调用:
AppLogServiceImpl appLogService = (AppLogServiceImpl) ApplicationContextUtil.getBean("appLogServiceImpl");
Ps: getBean中名称是Service中的名称,如果Service中没有自定义名称,那就把实现类的首字母小写即可。