问题:service在平常的controller中可以用,但是在定时器的run方法中不能用。
原因:定时器继承了TimerTask之后,在定时器调用此方法后会直接执行execute方法,来不及执行@Autowired标注进行注入。
引入ApplicationContextUtil的工具类:
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 {
// TODO Auto-generated method stub
ApplicationContextUtil.applicationContext = applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
}
在run方法中作出以下定义:
QueryService queryService = (QueryService)ApplicationContextUtil.getBean("queryService");
注:在service实现类中@Service必须写明要注入的名称
@Service(queryService)
public class QueryService {
}