Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the name of an injected service in grails

Tags:

grails

service

Can't seem to find info on this, if you have some, please point me to the right thread/post/link!

I have a service, lets say it's called 'SomeServiceWithAReallyLongNameICannotChange'. Of course the normal way to use services is to allow grails to inject them using either typless or typed notation:

class SomeClass{
    //...
    def someServiceWithAReallyLongNameICannotChange
    //...
}

-- or --

class SomeClass{
    //...
    SomeServiceWithAReallyLongNameICannotChange someServiceWithAReallyLongNameICannotChange
    //...
}

What I would like to do is rename the service to something shorter, but only where I'm using it, as I cannot change the name of the actual service. I tried using 'as' notation like you do with imports, and I tried changing the name in the typed declaration, but none of these things seem to work. Is this possible?

I tried something like this:

class SomeClass{
    //...
    def someServiceWithAReallyLongNameICannotChange as SS
    //and I tried
    def SomeServiceWithAReallyLongNameICannotChange SS
    //no joy
    //...
}

Thanks for your help!

like image 648
Quad64Bit Avatar asked Dec 28 '22 06:12

Quad64Bit


1 Answers

The solution is to use autowire by type. By default grails uses autowire by name and hence you have to declare the service with the same name as the bean.

Here's example

class FooController {

  boolean byName = false  //set autowire by type
  SomeReallyLongService service

}
  1. You have to define a boolean variable byName and set it to false
  2. You can not use def but must use the actual type of the service when declaring the service
  3. It will enable autowire by type for whole controller, so all other dependencies will also be autowired by type

It is explained here

Update: It is even possible to use Autowired annotation along with Qualifier.

Example:

class MyController {

  @Autowired
  @Qualifier("myServiceWithDifferntName")
  def someService

}
like image 187
Sudhir N Avatar answered Jan 03 '23 01:01

Sudhir N