2011-02-13 61 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() { 
    ... 
}