如何在Grails中调试NPE?

时间:2011-02-13 12:06:00

标签: grails groovy

我尝试使用以下代码在Grails中执行原始SQL:

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)

1 个答案:

答案 0 :(得分:0)

很难说出你提供的有限代码会发生什么,但有些事情需要检查。服务是否使用类别范围字段“def plainSqlService”注入控制器,就像您在此处使用dataSource一样,或者您是否正在调用new PlainSqlService()?如果您正在创建一个新实例,那么将不会注入dataSource bean,并且groovy.sql.Sql构造函数不会失败,但查询将会失败。

要尝试的一件事是grails clean - 只要这样的事情不起作用,完全重新编译通常会有所帮助。

一个重要但不相关的观点 - 您不应该在服务中使用Closures。控制器和标签库要求使用Closure实现操作和标记,但Service只是Groovy中定义的Spring bean。 Spring对Closures一无所知,因为它们只是一个Groovy执行的字段,好像它是一个方法,所以你期望从Spring获得的任何代理(特别是事务行为,还有安全性和其他特性)都不会发生。只寻找方法。

因此newNum应声明为:

def newNum() {
   ...
}
相关问题