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);