How to inject two or more dependencies with the same name

Let's say you have two services named UserService and both are included in your Grails classpath. This can happen, for example if you have a "core" package, and an "application" package that extends services from "core".

Here's what that might look like in our case:

Well, if you try to use "UserService" in your Grails application like so, you will get an error saying that UserService cannot be found.

    def userService

That's because there was a name collision on UserService.

Spring accounts for this, and allows you to define your class for each bean name. In Grails, we can define our beans in the grails-app/conf/resources.groovy file.

Here's an example of what our resources.groovy file would look like:

beans = {
  // syntax is beanId(implementingClassName) { properties }
  // User Service
  coreUserService( {
    grailsApplication = ref("grailsApplication")
  userService( {
    coreUserService = ref("coreUserService")

Then, in your services, you can inject these services like so:

class UserController {
  def userService


// From your UserService, you can access the core UserService like this.
class UserService {
  def coreUserService


Hopefully, that helps.

Leave a Reply