thomers
thomers

Reputation: 2693

Using a service from a non-Spring Groovy class

I am implementing a custom InteractiveAuthenticationSuccessEventListener to react on events from the spring-security-core plugin - the source file is in /src/groovy

In this class, how can I use a service defined in grails-app/services ? Dependency-injection (obviously?) does not work.

Upvotes: 2

Views: 650

Answers (1)

Dónal
Dónal

Reputation: 187499

Here are two options

  1. pass the dependencies into the class
  2. retrieve the spring bean within the class using a helper class such as

import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
import org.codehaus.groovy.grails.web.context.ServletContextHolder
import org.springframework.context.ApplicationContext

public class SpringUtils {

    static getSpringBean(String name) {
        getApplicationContext().getBean(name);
    }

    static ApplicationContext getApplicationContext() {
        return ServletContextHolder.getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
    }    
}

The first option is better IMO

Upvotes: 4

Related Questions