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

﹥>﹥吖頭↗ 提交于 2021-01-28 20:44:00

问题


I have a domain class named ABCDCode and created a service for the this ABCDCodeService. Now I want to use this service in controllers so I wrote it like below:

class TestController{
      ABCDCode abcdCode

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

I am suspecting something wrong with the autowiring by name.


回答1:


Grails looks first two characters for beans naming. If the second character of the controller/service is capital then Grails did not convert the first character to lower case.

e.g., TestService bean name is testService and TEstService bean name is TEstService.

So, your code becomes

ABCDCode ABCDCode

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

But if you want to user abcdCode as bean name, then you can do this with the help of resources.groovy. Add the following to your resources.groovy file--

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



回答2:


class TestController{
  ABCDCode aBCDCode
}

should work




回答3:


You have multiple issues.

1) You assign a member variable but it is never initialized, therefore you get a NullPointerException. You need to get the instance from your database by id first.

2) Be aware that the controller needs to be thread-safe, by assigning the member variable in the controller scope it will be used for many calls at the same time with unpredictible outcome.

3) Names like ABCDCode are against grails naming conventions. Use AbcdCode for the domain and AbcdCodeService for the service and all is well.

This would be the correct approach with the domain class AbcdCode and the corresponding service 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() 
  }

}



来源:https://stackoverflow.com/questions/50810310/how-to-autowire-a-service-in-grails-2-5-5-with-multiple-capital-letters-at-fro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!