I am trying to inject a service dependency in the constructor for another service.(see example code below). However, a NoSuchBeanDefinitionException is throws when I try to assign the api variable, even if the bean variable is set correctly.
It could also be worth to mention that this occur when I extend this service and initializing the child service.
My question is then, how could I proper inject the dependency service into my class dependent on the setting in my Config.groovy?
class MyService {
def api
public MyService() {
def beanString = ConfigurationHolder.config.api
def bean = ApplicationHolder.application.getMainContext().getBean(GrailsNameUtils.getPropertyName(beanString))
this.api = bean
}
}
EDIT: To clarify my idea. I have two API:s, one XML and one JSON that serves the same data, but with different representations. However, I want to be able to set the api to use in the configuration file, eg a string with the api-name.
My idea is to have a common interface for the available apis (ApiInterface) and then when my service that uses the api is initialized, set an instance variable to the configured api.
In addition to this, I want to be able to have service specific settings i.e. a setting for each service that injects the api in the configuration file that sets which api to use.
e.g.
Config.groovy
firstService {
api = "xml"
}
secondService {
api = "json"
}
I doubt you can get this to work without a lot of trouble since the instance is created by Spring when building the beans, so the other bean probably isn’t available yet. You could look it up lazily on first request though: