我有一个名为ABCDCode的域类,并为此ABCDCodeService创建了一个服务。现在我想在控制器中使用这个服务,所以我写的如下:
HTTP/1.1 200 OK
Date: Tue, 12 Jun 2018 06:13:05 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Content-Length: 4
null
我怀疑名字自动装配有问题。
答案 0 :(得分:2)
class TestController{
ABCDCode aBCDCode
}
应该有效
答案 1 :(得分:1)
您有多个问题。
1)您分配了一个成员变量但它从未被初始化,因此您会得到一个NullPointerException。您需要首先通过id从数据库中获取实例。
2)请注意控制器需要是线程安全的,通过在控制器范围内分配成员变量,它将同时用于许多调用,并产生不可预测的结果。
3)像ABCDCode这样的名称是针对grails命名约定的。使用AbcdCode作为域,使用AbcdCodeService作为服务,一切都很好。
这将是域类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()
}
}
答案 2 :(得分:0)
Grails查找bean命名的前两个字符。如果控制器/服务的第二个字符是大写,则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'
}