I’m using Grails 1.2.1. I have a class in my src/groovy file in which I’d like to inject a reference to a service. So I have …
def utilityService
public HttpTransporter(URI uri, HttpServletResponse response) {
this.uri = uri;
this.response = response;
def ctx = ApplicationHolder.getApplication().getMainContext();
utilityService = ctx.getBean("utilityService");
} // HttpTransporter
But this seems very anti-Groovy/Grails. Also, I don’t like creating a new instance of the service upon every class instantiation. Any ideas on how to optimize this?
Thanks, – Dave
You’re not creating a new instance of the service when calling getBean(), just getting a reference to the singleton. If the bean were a prototype bean then you’d get new instances, but Grails services aren’t – they’re singletons.
This isn’t very ‘groovy’ but you’re accessing Spring beans outside of an artifact, so you either need to pull the beans in from the application context like you’re doing, or pass the beans in when you call HttpTransporter. Ideally you could rework your calling code so you provide the dependencies rather than having to pull them:
If you can’t do that (you don’t show any calling code so it’s not clear if it’d be practical) then yes, you do need to use a less elegant approach.