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中没有自定义名称,那就把实现类的首字母小写即可。

 

转自:https://www.cnblogs.com/doudou2018/p/10416043.html

posted @ 2019-11-20 13:01  julian_chang  阅读(1500)  评论(0编辑  收藏  举报