多线程里面不能注入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");

版权声明:本文为WeiHao0240原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。