Timer定时任务中无法调用Mapper接口对象的问题

Timer定时器执行定时任务, 在service实现类中无法调用自动装载(@Autowired)的Mapper类。

timer中识别自动装载的mapper类未实例化,找不到实例化的bean,mapper对象为空。

参考别人的做法是提供一个工具类去帮助我们实例化mapper接口类

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

@Component
public class SpringContextHolder implements ApplicationContextAware {

private static ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}

public static void setContext(ApplicationContext applicationContext) {
if (SpringContextHolder.applicationContext == null) {
SpringContextHolder.applicationContext = applicationContext;
}
}

public static ApplicationContext getApplicationContext() {
assertApplicationContext();
return applicationContext;
}

@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName) {
assertApplicationContext();
return (T) applicationContext.getBean(beanName);
}

public static <T> T getBean(Class<T> requiredType) {
assertApplicationContext();
return applicationContext.getBean(requiredType);
}

private static void assertApplicationContext() {
if (SpringContextHolder.applicationContext == null) {
throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
}
}

}

在使用timer时,需要使用mapper对象的时候,使用该工具类对mapper接口实例化即可。

OrderInfoMapper orderMapper = springContextHolder.getBean(OrderInfoMapper.class);

猜你喜欢

转载自www.cnblogs.com/aaron95/p/11941272.html
今日推荐