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(); 調用
相關文章
相關標籤/搜索