代码之家  ›  专栏  ›  技术社区  ›  Ashu

如何在Grails(2.5.5)中自动连接前面有多个大写字母的服务

  •  1
  • Ashu  · 技术社区  · 8 年前

    我有一个名为abcdo代码的域类,并为此abcdo代码服务创建了一个服务。现在我想在控制器中使用这个服务,所以我写了如下:

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

    我怀疑自动布线有什么问题。

    3 回复  |  直到 8 年前
        1
  •  1
  •   MKB    8 年前

    Grails看起来是bean命名的前两个字符。如果控制器/服务的第二个字符是大写,那么Grails没有将第一个字符转换为小写。

    例如,testservice bean name是testservice,testservice bean name是testservice。

    所以,你的代码变成

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

    但是如果你想使用 abcdCode 作为bean名称,那么您可以在 resources.groovy .将以下内容添加到 资源.groovy 文件--

    beans = {
        springConfig.addAlias 'abcdCode', 'ABCDCode'
    }
    
        2
  •  2
  •   injecteer    8 年前
    class TestController{
      ABCDCode aBCDCode
    }
    

    应该工作

        3
  •  2
  •   chriopp    8 年前

    您有多个问题。

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

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

    3)类似abcdo代码的名称违反了Grails命名约定。对域使用cai代码,对服务使用cai代码,一切都很好。

    这是域类abcdo代码和相应服务abcdo代码服务的正确方法:

    // 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() 
      }
    

    }

    推荐文章