我是靠谱客的博主 高大咖啡,最近开发中收集的这篇文章主要介绍线程中调用service失败,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

在线程中使用spring注解注入service,使用的时候会发现通过注解注入的service一直是null,原因是程序启动的时候,线程中是防注入的。所以可以通过以下两个方法进行调用service:

1、将service当成参数传值

public class ThreadATestAction  extends Thread{

    private QueryReportService queryReportService;
    
    public ThreadATestAction(QueryReportService queryReportService){
        this.queryReportService=queryReportService;
        
    }
   
    @Override
    public  void run()
    {
        Map<String, Object> map=new HashMap<String, Object>();
        queryReportService.findAllReportIssued(map);

}

}

 

2、通过spring bean工厂 实例化类

     1)新建类,编写getbean 方法

/**
 * 

* <p>Title: AllBean</p>  

* <p>Description:线程内防注入,此方法注入service层 </p>  

 */
public class AllBean implements ApplicationContextAware{
       
    private static ApplicationContext applicationContext; 
   
    public void setApplicationContext(ApplicationContext context) {
       AllBean.applicationContext = context;
       }
   
    public static Object getBean(String name){
         return applicationContext.getBean(name);
    }
    
     public static ApplicationContext getApplicationContext() {  
          return applicationContext;  
      }  
}

    2)在spring配置中注册

<bean id="allBean" class="com.magingunion.framework.util.AllBean"  />

    3)线程中使用

QueryReportService queryReportService=(QueryReportService) AllBean.getBean("queryReportService"); 

注意(在service层中加入@Service注解后定义的service名字和上面的getBean的名字需保持一致)

最后

以上就是高大咖啡为你收集整理的线程中调用service失败的全部内容,希望文章能够帮你解决线程中调用service失败所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(80)

评论列表共有 0 条评论

立即
投稿
返回
顶部