简体   繁体   English

使用非Spring Groovy类中的服务

[英]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 我正在实现一个自定义的InteractiveAuthenticationSuccessEventListener以对spring-security-core插件中的事件做出反应-源文件位于/ src / groovy中

In this class, how can I use a service defined in grails-app/services ? 在此类中,如何使用grails-app / services中定义的服务? Dependency-injection (obviously?) does not work. 依赖注入(显然吗?)不起作用。

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 使用诸如以下的辅助类在类中检索spring bean

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 第一个选择是更好的IMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM