2011-02-13 63 views
0

我嘗試執行原始SQL Grails中使用此代碼:
如何在Grails中調試NPE?

class PlainSqlService { 

    def dataSource // the Spring-Bean "dataSource" is auto-injected 

    def newNum = { 
     def sql = new Sql(dataSource) // Create a new instance of groovy.sql.Sql with the DB of the Grails app 
     def q = "SELECT a.xaction_id, a.xdin FROM actions a WHERE a.is_approved = 0" 
     def result = sql.rows(q) // Perform the query 
       return result 
    } 
} 

,但我得到這個例外在運行時。
sql對象不爲null!
我該如何調試?

2011-02-13 15:55:27,507 [http-8080-1] ERROR errors.GrailsExceptionResolver - Exception occurred when processing request: [GET] /moderator/login/index 
Stacktrace follows: 
java.lang.NullPointerException 
    at moderator.PlainSqlService$_closure1.doCall(PlainSqlService.groovy:17) 
    at moderator.PlainSqlService$_closure1.doCall(PlainSqlService.groovy) 
    at moderator.LoginController$_closure1.doCall(LoginController.groovy:29) 
    at moderator.LoginController$_closure1.doCall(LoginController.groovy) 
    at java.lang.Thread.run(Thread.java:662) 
+4

你必須在全部源貼,如果你想使用一個堆棧跟蹤調試任何幫助:

所以newNum如要申報。否則,那些行號就沒有意義 - 除非你期待我們的心理調試。 – Chii 2011-02-13 12:45:39

回答

0

很難說出您提供的有限代碼是怎麼回事,但有一些事情需要檢查。是否將服務注入到控制器中,並使用類範圍字段「def plainSqlService」(就像您在此處爲dataSource所做的那樣),還是要調用new PlainSqlService()?如果你正在創建一個新的實例,那麼dataSource bean將不會被注入,並且groovy.sql.Sql構造函數不會失敗,但是查詢會。

有一點要嘗試的是grails clean - 只要像這樣的工作不應該,一個完整的重新編譯通常會有所幫助。

一個重要但不相關的問題 - 你不應該在服務中使用閉包。控制器和標籤庫要求使用Closure實現動作和標籤,但Service只是Groovy中定義的一個Spring bean。 Spring對閉包一無所知,因爲它們只是Groovy執行的一個字段,就像它是一種方法一樣,所以從Spring期望的任何代理(特別是事務行爲,還有安全性和其他功能)都不會發生,因爲Spring只查找方法。

def newNum() { 
    ... 
}