在控制器中调用服务时,无法在null对象上调用方法pullLogs()

时间:2013-05-10 17:53:06

标签: grails service

我已经搜索了堆栈溢出并找到了一些类似我的问题的实例,但是修复完成似乎对我有用。 (类似的例子:Grails - Can't call service from Controller --> always get "Cannot invoke method on null object error"

我的服务可以这样总结

class AuditService {


  AuditService auditService

  def sql
  def dataSource
  static transactional = true


  def pullLogs(String username, String id) { 
    if(username != null && id != null) {

        sql = new Sql(dataSource)
        println "Data source is: " + dataSource.toString()
        def schema = dataSource.properties.defaultSchema

        sql.query('select USERID, AUDIT_DETAILS from DEV.AUDIT_LOG T WHERE XMLEXISTS(\'\$s/*/user[id=\"' + id + '\" or username=\"'+username+'\"]\' passing T.AUDIT_DETAILS as \"s\") ORDER BY AUDIT_EVENT', []) { ResultSet rs ->
            while (rs.next()) { 
                def auditDetails = new XmlSlurper().parseText(rs.getString('AUDIT_EVENT_DETAILS'))
                println auditDetails
            }
        }
        sql.close()
    }
}

}

我试图调用它的方式就像这样

UserController {

  def auditService


  show(Long id){

    def UserInstance = User.get(id)

    //Also tried def auditResults = auditServices.pullLogs(UserInstance.username, UserInstance.id)
    def auditResults = auditServices(UserInstance.username, UserInstance.id)
    System.out.println(" "+ auditResults)
    [UserInstance: UserInstance,params:params]
  }
}

我得到的错误是

Class:
java.lang.NullPointerException
Message:
 Cannot invoke method pullLogs() on null object

我很难过。 (询问给了我)

任何想法/意见/帮助都很受欢迎!

谢谢!

2 个答案:

答案 0 :(得分:3)

在UserController中你有

def auditService

但是

def auditResults = auditServices(UserInstance.username, UserInstance.id)

应该是

def auditResults = auditService.pullLogs(UserInstance.username, UserInstance.id)

至于“FactoryBean not initialized”错误,为此你可以简单地删除

AuditService auditService

来自AuditService内部 - 如果您需要在自己的代码中引用AuditService,则无需使用this

答案 1 :(得分:1)

您的服务名称是LogService还是AuditService?如果它是AuditService,则控制器中的属性名称不应包含s

class UserController {
  def auditService //Name should be the same of the service, not in plural
  ...
}