spring中静态方法调用Mapper,Service

1.需求

在工做中经常会有在工具类中使用数据库数据的情景,工具类中方法一般是静态方法,因此问题来了,静态方法中是不能引用mapper或者service的。废话不说,上代码。java

2.代码

package com.noahedu.education.persistences;

import com.noahedu.download.mapper.CacheMapper;
import com.noahedu.download.util.SpringUtil;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Class DictionariesHelper application-context.xml 配置随项目启动加载机型字典 <bean id="productCache"
 * lazy-init="false" class="com.noahedu.education.persistences.DictionariesHelper"
 * init-method="productDictionaryInit"/> 
 *
 * @author gaobo
 * @date 2019/6/21
 */
@Component
public class DictionariesHelper {

  private static DictionariesHelper dictionariesHelper;
  //  全局机型字典
  private static List<ProductDictionary> productDictionaries;
  @Autowired
  CacheMapper cacheMapper;

  /**
   * 随项目启动初始化 productDictionaries 字典
   */
  //每隔5分钟执行一次定时任务
  @Scheduled(cron = "* 0/5 * * * ?")
  public static void productDictionaryInit() {
    productDictionaries = dictionariesHelper.cacheMapper.selectProductDic();
  }

  @PostConstruct
  public void init() {
    dictionariesHelper = this;
    dictionariesHelper.cacheMapper = this.cacheMapper;
  }


}

3. 简要说明 

1. @Component 注解标注 DictionariesHelper 加载到spring中

2.  private static DictionariesHelper dictionariesHelper

3. @PostConstruct 注解做用是会在类加在是执行init方法  
    @PostConstruct 
    public void init() { 
       dictionariesHelper = this; 
       dictionariesHelper.cacheMapper = this.cacheMapper;       
    }
4.  使用 dictionariesHelper.cacheMapper.selectProductDic(); 调用
相关文章
相关标签/搜索