2015-09-26 90 views
1

我註釋一個Thread類如下:春天JPA主題:拋出:IllegalArgumentException異常

@Transactional(propagation = Propagation.REQUIRED) 
@Component 
@Scope("prototype") 
public class ThreadRetrieveStockInfoEuronext implements Runnable { 
    ... 
} 

線程通過Global.poolMultiple.execute(threadRetrieveStockInfoEuronext)連線到控制器類,並呼籲;

public class RetrievelController { 

    @Autowired 
    private ThreadRetrieveStockInfoEuronext threadRetrieveStockInfoEuronext; 

    @RequestMapping(value = "/.retrieveStockInfo.htm", method = RequestMethod.POST) 
    public ModelAndView submitRetrieveStockInfo(@ModelAttribute("retrieveStockInfoCommand") RetrieveStockInfoCommand command, BindingResult result, HttpServletRequest request) throws Exception { 

     Global.poolMultiple.execute(threadRetrieveStockInfoEuronext); 
     return new ModelAndView(".retrieveStockInfo", "retrieveStockInfoCommand", command); 
    } 

全球類:

@SuppressWarnings("unchecked") 
@Component 
public class Global { 

    // create ExecutorService to manage threads 
    public static ExecutorService poolMultiple = Executors.newFixedThreadPool(10); 
    public static ExecutorService poolSingle = Executors.newFixedThreadPool(1); 
... 
} 

運行應用程序時,會出現以下異常:

java.lang.IllegalArgumentException異常:無法設置 com.chartinvest.admin。 thread.ThreadRetrieveStockInfoEuronext場

com.chartinvest.controller.RetrievelContr oller.threadRetrieveStockInfoEuronext 到com.sun.proxy。$ Proxy52

回答

3

那是因爲你的Runnable實現是Spring組件,與@Transactional註釋,以及聲明式事務都實現了,在春天,通過包裝的實際實例類處理事務的基於JDK接口的代理中的類。結果,即自動裝配實際的對象不是ThreadRetrieveStockInfoEuronext的實例,但它的接口,可運行的實例,委託給ThreadRetrieveStockInfoEuronext的一個實例。

通常修復到這個問題是自動裝配的接口,而不是自動裝配具體類型的。但是,在這種情況下,這個類不應該擺在首位Spring的組成部分,它不應該是事務要麼。 BTW,使得它的原型爲您提供了一個新的實例將每個submitRetrieveStockInfo()被調用時產生的幻覺,但這是不正確的:創建一個實例,並自動連接到RetrievelController單,因而同樣可運行用於所有請求給控制器。

只是要ThreadRetrieveStockInfoEuronext一個簡單的類,它使用新的,經過一個Spring bean作爲參數實例化,並使其run()方法調用的Spring bean的事務方法:

@Transactional 
@Component 
public class ThreadRetrieveStockInfoEuronextImpl implements ThreadRetrieveStockInfoEuronext { 
    @Override 
    void doSomething() { ... } 
} 

public class RetrievelController { 

    @Autowired 
    private ThreadRetrieveStockInfoEuronext threadRetrieveStockInfoEuronext; 

    @RequestMapping(value = "/.retrieveStockInfo.htm", method = RequestMethod.POST) 
    public ModelAndView submitRetrieveStockInfo(@ModelAttribute("retrieveStockInfoCommand") RetrieveStockInfoCommand command, BindingResult result, HttpServletRequest request) throws Exception { 

     Runnable runnable = new Runnable() { 
      @Override 
      public void run() { 
       threadRetrieveStockInfoEuronext.doSomething(); 
      } 
     }; 

     Global.poolMultiple.execute(runnable); 
     return new ModelAndView(".retrieveStockInfo", "retrieveStockInfoCommand", command); 
    } 
+0

非常感謝JB爲您的意見,該解決方案完美無缺! – user2023141

相關問題