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

本文介绍了一种在Spring框架下,解决Timer定时任务中自动装载(@Autowired)的Mapper类未实例化的问题。通过创建SpringContextHolder工具类,实现了在定时任务中对Mapper接口的实例化,确保了定时任务可以正确调用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);

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值