如何在前面有多个大写字母的 grails (2.5.5) 中自动装配服务

How to autowire a service in grails (2.5.5) with multiple capital letters at front

我有一个名为 ABCDCode 的域 class,并为此 ABCDCodeService 创建了一个服务。现在我想在控制器中使用这个服务,所以我这样写:

class TestController{
      ABCDCode abcdCode

      def index(int id){
           abcdCode.getData(id) //Here I am getting NullPOinterException
      }
}

我怀疑名称自动装配有问题。

class TestController{
  ABCDCode aBCDCode
}

应该可以

您有多个问题。

1) 您分配了一个成员变量,但它从未被初始化,因此您得到一个 NullPointerException。您需要先通过 id 从您的数据库中获取实例。

2) 请注意,控制器需要是线程安全的,通过在控制器范围内分配成员变量,它将同时用于许多调用,结果不可预测。

3) ABCDCode 之类的名称违反了 grails 命名约定。将 AbcdCode 用于域,将 AbcdCodeService 用于服务,一切正常。

这将是域 class AbcdCode 和相应服务 AbcdCodeService:

的正确方法
// if not in the same module
import AbcdCode

class TestController {

    // correct injection of the service
    def abcdCodeService 

    // ids are Long, but you could omit the type
    def index(Long id) {
       // get instance from database by id, moved to method scope
       def abcdCode = AbcdCode.get(id) 
       // note the "?." to prevent NullpointerException in case
       // an abcdCode with id was not found.
       def data = abcdCode?.getData() 
  }

}

Grails 查找 bean 命名的前两个字符。如果 controller/service 的第二个字符是大写,那么 Grails 不会将第一个字符转换为小写。

例如,TestService bean 名称是 testService,TEstService bean 名称是 TEstService。

因此,您的代码变为

ABCDCode ABCDCode

def index(int id){
    ABCDCode.getData(id)
}

但是如果你想使用 abcdCode 作为 bean 名称,那么你可以在 resources.groovy 的帮助下完成此操作。将以下内容添加到您的 resources.groovy 文件中--

beans = {
    springConfig.addAlias 'abcdCode', 'ABCDCode'
}