TimerタイミングタスクでMapperインターフェースが起動できない問題

1932 ワード

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 getBean(String beanName) {
        assertApplicationContext();
        return (T) applicationContext.getBean(beanName);
    }

    public static  T getBean(Class 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);