多线程里面不能注入Service或者Mapper

多线程里面不能注入Service或者Mapper

1.问题及原因

if(msg.contains("成功")) {
	Log log = new Log();
	log.setStatus(1);
	log.setUserId(Integer.parseInt(u.getStuNum()));
	log.setCreateTime(MyUtils.getNowDateTime());
	log.setCount(Integer.parseInt(seat));
	logService.addLog(log);
	break;
}	

本想通过注解的方式实现日志插入,
但是一直报空指针。
经过一段时间的百度已经试验,
终于调试成功。

2.解决方案

2.1新建一个工具类

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * class name: AppBean <BR>
 * class description: please write your description <BR>
 * @version 1.0  2019年4月2日 上午10:03:10
 * @author Aisino)Jack魏
 */
public class AppBean implements ApplicationContextAware {

	private static ApplicationContext applicationContext; 
	
	/**
	* @Override
	* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) <BR>
	* Method name: setApplicationContext <BR>
	* Description: please write your description <BR>
	* Remark: <BR>
	* @param applicationContext
	* @throws BeansException  <BR>
	*/
	@Override
	public void setApplicationContext(ApplicationContext appContext) throws BeansException {
		applicationContext = appContext;
	}
	
	public static Object getBean(String name){
        return applicationContext.getBean(name);
    }
    
     public static ApplicationContext getApplicationContext() {  
         return applicationContext;  
     }
}

2.2配置文件

在Config包下加一个Bean

	@Bean
	public AppBean appBean() {
		return new AppBean();
	}

或者在spring.xml里面加上

<bean id="AppBean" 
class="com.xxx.xxx.AppBean"/>

然后在线程里面加上下面语句,
再次调用即可。

private static LogService logService = (LogService) AppBean.getBean("logService");
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jack魏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值