線程中調用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的名字需保持一致)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章