Reputation: 12228
I have an abstract class that many classes extend. Everything is in src/groovy
.
In my abstract class I would like to have a service injected that the child classes would inherit so I don't have to inject them in every single one.
abstract class Animal {
def noiseService
abstract Sound getSound()
}
class Dog extends Animal {
Sound getSound() {
noiseService.bark()
}
}
In my resources.groovy:
animal(com.thepound.Animal) { bean ->
noiseService = ref("noiseService")
}
This produced an error saying it couldn't instantiate the class because it is abstract, so I added this to the definition:
bean.abstract = true
Now I no longer get an error, however the services are always null in my child classes. How can I get this to work?
Upvotes: 0
Views: 2462
Reputation: 12228
Here is what I ended up doing.
I followed Burt Beckwith's post here http://burtbeckwith.com/blog/?p=1017 to create an ApplicationContextHolder class.
Then
abstract class Animal {
def noiseService = ApplicationContextHolder.getBean("noiseService")
abstract Sound getSound()
}
Now this works
class Dog extends Animal {
Sound getSound() {
noiseService.bark()
}
}
I didn't have to put anything in resources.groovy for the Dog
or Animal
classes
Upvotes: 1
Reputation: 32066
If you want to instantiate Dog, just do this:
noiseService(com.whatever.DogNoiseService) { bean ->
}
animal(com.thepound.Dog) { bean ->
noiseService = ref("noiseService")
}
Upvotes: 0