springboot中非Controller调用service报空指针异常
package com.justsy.utils; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.justsy.entity.Patrol; import com.justsy.service.Potrol_Service; @Component //将工具类声明为spring组件 public class TestUtils { @Autowired private Potrol_Service pService; //静态初使化当前类 public static TestUtils testUtils; @PostConstruct public void init() { testUtils = this; testUtils.pService = this.pService; } //utils工具类中使用service或mapper接口的方法例子 public static void test(Patrol patral) { testUtils.pService.addPatrol(patral); } }
非controller调用
private void saveData() { //LOGGER.info("{}条数据,开始存储数据库!", list.size()); for (Patrol patral : list) { TestUtils.test(patral); } LOGGER.info("{}条数据存储成功!",list.size()); }
成功调用:
2019-10-15 16:58:47.090 DEBUG 92676 --- [io-8080-exec-14] c.j.mapper.Patrol_Mapper.insertPatrol : ==> Preparing: INSERT INTO justsafe_patrol ( project_id, net_info_id, patrol_time, cpu_usage_rate, ram_usage_rate, disk_Usage_Rate, disk_Home_Usage_Rate, nginx_http, nginx_https, nginx_Download, push ) values( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) 2019-10-15 16:58:47.093 DEBUG 92676 --- [io-8080-exec-14] c.j.mapper.Patrol_Mapper.insertPatrol : ==> Parameters: 1(Integer), 1000002(Integer), 2019-03-06 00:00:00.0(Timestamp), 11.0(Double), 22.0(Double), 33.0(Double), 44.0(Double), 55(Integer), 66(Integer), 77(Integer), 88(Integer) 2019-10-15 16:58:47.093 DEBUG 92676 --- [io-8080-exec-14] c.j.mapper.Patrol_Mapper.insertPatrol : <== Updates: 1 2019-10-15 16:58:47.093 INFO 92676 --- [io-8080-exec-14] c.j.utils.easyexcel.DemoDataListener : 1条数据存储成功! 2019-10-15 16:58:47.094 INFO 92676 --- [io-8080-exec-14] c.j.utils.easyexcel.DemoDataListener : 数据解析与存储操作已完成
下一篇:
将字母输入给int型变量的情况