服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - 解决SpringBoot项目使用多线程处理任务时无法通过@Autowired注入bean问题

解决SpringBoot项目使用多线程处理任务时无法通过@Autowired注入bean问题

2021-05-29 12:27Bug开发工程师 Java教程

这篇文章主要介绍了SpringBoot项目使用多线程处理任务时无法通过@Autowired注入bean问题的解决方法,需要的朋友可以参考下

最近在做一个“温湿度控制”的项目,项目要求通过用户设定的温湿度数值和实时采集到的数值进行比对分析,因为数据的对比与分析是一个通过前端页面控制的定时任务,经理要求在用户开启定时任务时,单独开启一个线程进行数据的对比分析,并将采集到的温湿度数值存入数据库中的历史数据表,按照我们正常的逻辑应该是用户在请求开启定时任务时,前端页面通过调用后端接口,创建一个新的线程来执行定时任务,然后在线程类中使用 @autowired 注解注入保存历史数据的service层,在线程类中调用service层保存历史数据的方法实现温湿度数据的保存,这时就出现了一个很尴尬的问题,在新开启的线程中使用 @autowired 注解无法注入需要的bean(即:保存历史数据的service层),程序一直在报 nullpointerexception

这是controller层,方法 startexperiment 和 stopexperiment 分别是开始定时任务和停止定时任务的方法,getdata方法不属于本次讨论范围,不用管

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.backstage.controller;
import com.alibaba.fastjson.jsonobject;
import com.backstage.entity.jsonresponse;
import com.backstage.entity.threshold;
import com.backstage.service.mainpageservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
import javax.servlet.http.httpservletrequest;
/**
 * @projectname:
 * @package: com.backstage.controller
 * @classname: mainpagecontroller
 * @description: 主页面相关操作控制器
 * @author: wangzhilong
 * @createdate: 2018/8/29 9:49
 * @version: 1.0
 */
@restcontroller
@requestmapping("/main")
public class mainpagecontroller {
 @autowired
 private mainpageservice mainpageservice;
 /**
  * 开始实验
  *
  * @param threshold
  */
 @requestmapping("/startexperiment")
 public jsonresponse startexperiment(httpservletrequest request, threshold threshold) {
  return mainpageservice.startexperiment(request, threshold);
 }
 /**
  * 停止实验
  */
 @requestmapping("/stopexperiment")
 public jsonresponse stopexperiment() {
  return mainpageservice.stopexperiment();
 }
 /**
  * 获取实时数据
  *
  * @return
  */
 @requestmapping("/getdata")
 public jsonobject getdata() {
  return null;
 }
}

 service 层接口代码,没什么好说的,直接上代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.backstage.service;
import com.alibaba.fastjson.jsonobject;
import com.backstage.entity.jsonresponse;
import com.backstage.entity.threshold;
import javax.servlet.http.httpservletrequest;
/**
 * @projectname:
 * @package: com.backstage.service
 * @classname: mainpageservice
 * @description: 主页面相关操作业务层接口
 * @author: wangzhilong
 * @createdate: 2018/8/29 9:51
 * @version: 1.0
 */
public interface mainpageservice {
 /**
  * 开始实验
  *
  * @param threshold
  */
 jsonresponse startexperiment(httpservletrequest request, threshold threshold);
 /**
  * 停止实验
  */
 jsonresponse stopexperiment();
 /**
  * 获取实时数据
  *
  * @return
  */
 jsonobject getdata();
}

 

 service 层实现类代码,关于springboot项目使用多线程进行业务处理不属于本章节的讨论范围,如有需要,请留言,我会在看到留言后第一时间更新相关技术文章,由于这里删除了一些与本章节无关的代码,如果复制到开发工具内有报错问题,麻烦大家提醒我一下,以便修改,非常感谢

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.backstage.service.impl;
import com.alibaba.fastjson.jsonobject;
import com.backstage.entity.*;
import com.backstage.monitor.timingmonitoring;
import com.backstage.service.*;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.bean;
import org.springframework.scheduling.trigger;
import org.springframework.scheduling.triggercontext;
import org.springframework.scheduling.concurrent.threadpooltaskscheduler;
import org.springframework.scheduling.support.crontrigger;
import org.springframework.stereotype.service;
import javax.servlet.http.httpservletrequest;
import java.text.simpledateformat;
import java.util.date;
import java.util.list;
import java.util.concurrent.scheduledfuture;
/**
 * @projectname:
 * @package: com.backstage.service.impl
 * @classname: mainpageserviceimpl
 * @description: 主页面相关操作业务层实现类
 * @author: wangzhilong
 * @createdate: 2018/8/29 9:51
 * @version: 1.0
 */
@service
public class mainpageserviceimpl implements mainpageservice {
 @autowired
 private threadpooltaskscheduler threadpooltaskscheduler;
 private scheduledfuture<?> future2;
 @bean
 public threadpooltaskscheduler threadpooltaskscheduler() {
  return new threadpooltaskscheduler();
 }
 /**
  * 开始实验
  *
  * @param threshold
  */
 @override
 public jsonresponse startexperiment(httpservletrequest request, threshold threshold) {
  timingmonitoring timingmonitoring = new timingmonitoring();
  timingmonitoring.setthreshold(threshold, list, experiment.getid(), experimentdata.getid());
  future2 = threadpooltaskscheduler.schedule(new timingmonitoring(), new trigger() {
   @override
   public date nextexecutiontime(triggercontext triggercontext) {
    //设置定时任务的执行时间为3秒钟执行一次
    return new crontrigger("0/10 * * * * ?").nextexecutiontime(triggercontext);
   }
  });
  return new jsonresponse(0,"开始实验!");
 }
 /**
  * 停止实验
  */
 @override
 public jsonresponse stopexperiment() {
  if (future2 != null) {
   experimentservice.upd(gettime());
   future2.cancel(true);
  }
  return new jsonresponse(0,"结束实验!");
 }
 /**
  * 获取实时数据
  *
  * @return
  */
 @override
 public jsonobject getdata() {
  return null;
 }
 protected string gettime() {
  simpledateformat format = new simpledateformat("yyyy-mm-dd hh:mm:ss");
  return format.format(new date());
 }
}

重点,线程类代码,大家注意看,我在代码最开始使用了spring的 @autowired 注解注入需要的service,可在调用service中的add方法时,程序报空指针异常,一直认为是add方法或者sql语句有问题,找了一上午,也没发现任何问题,后来单独调用这个add方法是可以正常插入数据的,唯独在这个线程类中调用时报错,感觉和线程有莫大的关系,百度一搜,还真找到了,原来,在线程中为了线程安全,是防注入的,没办法,要用到这个类啊。只能从bean工厂里拿个实例了,继续往下看

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.backstage.monitor;
import com.backstage.entity.detaileddata;
import com.backstage.entity.threshold;
import com.backstage.entity.valvevalue;
import com.backstage.service.detaileddataservice;
import java.text.simpledateformat;
import java.util.date;
import java.util.list;
/**
 * @projectname:
 * @package: com.backstage.monitor
 * @classname: timingmonitoring
 * @description: 定时监测温(湿)度 数据
 * @author: wangzhilong
 * @createdate: 2018/8/29 10:11
 * @version: 1.0
 */
public class timingmonitoring implements runnable{
 //历史数据业务层接口
 @autowired
 public detaileddataservice detaileddataservice;
 private threshold threshold;   //阈值实体类
 private list<valvevalue> settingdata; //设定的温湿度数据
 private integer id;      //实验记录id
 private integer dataid;     //历史数据主表id
 
 public void setthreshold(threshold threshold, list<valvevalue> settingdata, integer id, integer dataid) {
  this.threshold = threshold;
  this.settingdata = settingdata;
  this.id = id;
  this.dataid = dataid;
 }
 @override
 public void run() {
  //模拟从plc获取到的数据
  string data = "001,50.5,002,37,003,45.6,004,40,005,55.2,006,58";
  if (data == null || data.trim() == "") {
   return; //若获取到的数据为空,则直接停止该方法的执行
  }
  double temperature = 0.0; //温度
  double humidity = 0.0//湿度
  integer type = null;    //数据类型,1是温度,2是湿度
  //解析数据,并将数据保存到历史数据数据库
  string[] str = data.split(",");
  simpledateformat format = new simpledateformat("yyyy-mm-dd hh:mm:ss:ss");
  for (int i = 0; i < str.length; i++) {
   if (i == 1 || i == 5 || i == 9) { //温度
    type = 1;
    temperature += double.parsedouble(str[i]);
    //system.out.println("温度" + i + " -》 " + str[i-1] + ":" + str[i]);
    detaileddataservice.add(new detaileddata(null, type, double.parsedouble(str[i]), format.format(new date()), str[i - 1], dataid));
   }
   if (i == 3 || i == 7 || i == 11) { //湿度
    type = 2;
    humidity += double.parsedouble(str[i]);
    //system.out.println("湿度" + i + " -》 " + str[i-1] + ":" + str[i]);
    detaileddataservice.add(new detaileddata(null, type, double.parsedouble(str[i]), format.format(new date()), str[i - 1], dataid));
   }
  }
 }
 /**
  * 获取当前时间,精确到毫秒
  * @return
  */
 protected string gettime() {
  simpledateformat format = new simpledateformat("yyyy-mm-dd hh:mm:ss:ss");
  return format.format(new date());
 }
}

获取bean对象的工具类,既然程序无法通过注解拿到需要的bean,那就只好自己写个工具类来获取喽,下面是工具类代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.backstage.config;
import org.springframework.beans.beansexception;
import org.springframework.context.applicationcontext;
import org.springframework.context.applicationcontextaware;
import org.springframework.stereotype.component;
/**
 * @projectname:
 * @package: com.backstage.config
 * @classname: applicationcontextprovider
 * @description: 获取bean对象的工具类
 * @author: wangzhilong
 * @createdate: 2018/8/31 13:26
 * @version: 1.0
 */
/**
 * author:zhushangjin
 * date:2018/7/3
 */
@component
public class applicationcontextprovider implements applicationcontextaware {
 /**
  * 上下文对象实例
  */
 private static applicationcontext applicationcontext;
 @override
 public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {
  this.applicationcontext = applicationcontext;
 }
 /**
  * 获取applicationcontext
  *
  * @return
  */
 public static applicationcontext getapplicationcontext() {
  return applicationcontext;
 }
 /**
  * 通过name获取 bean.
  *
  * @param name
  * @return
  */
 public static object getbean(string name) {
  return getapplicationcontext().getbean(name);
 }
 /**
  * 通过class获取bean.
  *
  * @param clazz
  * @param <t>
  * @return
  */
 public static <t> t getbean(class<t> clazz) {
  return getapplicationcontext().getbean(clazz);
 }
 /**
  * 通过name,以及clazz返回指定的bean
  *
  * @param name
  * @param clazz
  * @param <t>
  * @return
  */
 public static <t> t getbean(string name, class<t> clazz) {
  return getapplicationcontext().getbean(name, clazz);
 }
}

这样呢,就可以在线程类中写一个无参的构造方法,在构造方法中,通过调用工具类中的 getbean() 方法就可以拿到实例了,程序在调用这个线程类时,会自动调用其无参的构造方法,在构造方法中我们将需要的bean对象注入,然后就可以正常使用了,下边是线程类修改后的代码,由于别的地方没有改动,所以这里只给大家改动的代码,省得大家看到一大堆代码头疼。

?
1
2
3
4
public timingmonitoring() {
  //new的时候注入需要的bean
  this.detaileddataservice = applicationcontextprovider.getbean(detaileddataservice.class);
 }

总结

以上所述是小编给大家介绍的springboot项目使用多线程处理任务时无法通过@autowired注入bean 问题,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

原文链接:https://www.cnblogs.com/xiaolong1996/archive/2018/09/01/9571645.html

延伸 · 阅读

精彩推荐