当前位置:网站首页>Service or mapper cannot be injected into a multithread

Service or mapper cannot be injected into a multithread

2022-06-22 17:06:00 51CTO


Multiple threads cannot be injected Service perhaps Mapper


1. Problems and causes

      
      
if( msg. contains( " success ")) {
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;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

I wanted to realize log insertion through annotation ,
But the null pointer is always reported .
After a period of time, Baidu has tried ,
Finally, the debugging is successful .

2. Solution

2.1 Create a new tool class

      
      
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 year 4 month 2 Japan In the morning 10:03:10
* @author Aisino)Jack wei
*/
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;
}
}
  • 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.

2.2 The configuration file

stay Config Add one under the package Bean

      
      
@Bean
public AppBean appBean() {
return new AppBean();
}
  • 1.
  • 2.
  • 3.
  • 4.

Or in spring.xml Inside plus

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

Then add the following statement to the thread ,
Call again .

      
      
private static LogService logService = ( LogService) AppBean. getBean( "logService");
  • 1.


原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221532330574.html