Reputation: 568
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!
Upvotes: 4
Views: 2855
Reputation: 4096
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
}
It is explained here
Update: It is even possible to use Autowired annotation along with Qualifier.
Example:
class MyController {
@Autowired
@Qualifier("myServiceWithDifferntName")
def someService
}
Upvotes: 6
Reputation: 528
I tried it and it's not working for me on Grails 3, did this by doing
import org.springframework.beans.factory.annotation.Autowired
...
@Autowired
PaymentStrategyService paymentStrategySvc
Upvotes: 0
Reputation: 39570
Another option, if you don't want to use autowire by type through the whole controller, nor do you want to add a custom bean for some reason, is to add a simple method to your controllers where you need the service, like so:
def someServiceWithAReallyLongNameICannotChange
def getSS() { someServiceWithAReallyLongNameICannotChange }
Then you could reference the service using ss.someMethod()
anywhere within that controller.
However, this still requires you to add a chunk of code for every controller you use this service, or you will have inconsistent naming of the service.
(Personally, I think that doelleri's method is the best, since it allows you to be consistent in naming without modifying individual classes.)
Upvotes: 1
Reputation: 19682
You should be able to create a new bean via resources.groovy
beans = {
ss(SomeServiceWithAReallyLongNameICannotChange)
}
You can then inject it normally:
class SomeClass {
//...
def ss
//...
}
Upvotes: 3