Home » JVM Languages » Groovy » The Grails depedency injection inheritance pitfall

About Michael Scharhag

Michael Scharhag
Michael Scharhag is a Java Developer, Blogger and technology enthusiast. Particularly interested in Java related technologies including Java EE, Spring, Groovy and Grails.

The Grails depedency injection inheritance pitfall

This blog post is about a small pitfall you should be aware of when combining dependency injection in Grails with inheritance.

I think the problem is best explained with a piece of example code. So let’s look at the following two definitions of Grails controllers.

class FooController {
  TestService testService

  def foo() {
    // do something with testService
class BarController extends FooController {
  TestService testService

  def bar() {
    // do something with testService

Both controllers look nearly identical. The only difference is that BarController extends FooController. Now assume we have an instance of BarController and we want to call the methods bar() and foo() on it. Guess what happens?

The call of bar() works fine while the call of foo() throws a NullPointerException because testService is null.

testService is a standard Groovy property. This means that the testService fields will become private and getter / setter methods are generated for both controllers. The getter / setter of BarController override the getter / setter of FooController. So whenever the dependency is injected using setTestService() only BarController retrieves the TestService instance. This is nothing special about Grails controllers, it works the same for services and other Groovy classes.

The solution is easy: Remove the testService dependency from BarController. Whenever testService is accessed in BarController, it will use the appropriate getter of FooController and everything works.

In this simple example the problem is quite obvious and can be easily solved. However, if your classes become larger this can be a bit tricky to debug. Assume you have a base class with multiple sub classes. Whenever you want to add a new dependency to your base class, you have to check all the subclasses. If one of the sub classes already defines the same dependency you have to remove it or it will not be available in your base class.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Notify of