springboot 自定義工具類調用service層


springboot自定義工具類中,如果想調用service層方法,是不能使用傳統方式實現的,比如@Autowired HolidayService holidayService或者new HolidayServiceImpl(),需要特殊的配置才能實現調用,否則報null指針異常

第一步,在工具類上加注解@Component,將工具類交由Spring容器管理

@Component
public class HolidayUtil{

}

第二步,注入需要調用的Service類,並給當前工具類定義一個靜態參數

@Component
public class HolidayUtil{
    @Autowired
    HolidayService holidayService;

    private static HolidayUtil holidayUtil;
}

第三步,初始化參數值

@Component
public class HolidayUtil{
    @Autowired
    HolidayService holidayService;

    private static HolidayUtil holidayUtil;

    @PostConstruct
    public void init(){
        holidayUtil = this;
        holidayUtil.holidayService = this.holidayService;
    }
}

第四步,進行調用

// 使用holidayUtil.holidayService調用Service層方法
List<Holiday> holidayList =holidayUtil.holidayService.getHolidayList(startTime, endTime);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM