刚刚检查了我现有的一些代码,我使用了 Burt Beckwith 描述的这种方法
创建一个新文件: src/groovy/ctx/ApplicationContextHolder.groovy
package ctx
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import javax.servlet.ServletContext
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.plugins.GrailsPluginManager
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
@Singleton
class ApplicationContextHolder implements ApplicationContextAware {
private ApplicationContext ctx
private static final Map<String, Object> TEST_BEANS = [:]
void setApplicationContext(ApplicationContext applicationContext) {
ctx = applicationContext
}
static ApplicationContext getApplicationContext() {
getInstance().ctx
}
static Object getBean(String name) {
TEST_BEANS[name] ?: getApplicationContext().getBean(name)
}
static GrailsApplication getGrailsApplication() {
getBean('grailsApplication')
}
static ConfigObject getConfig() {
getGrailsApplication().config
}
static ServletContext getServletContext() {
getBean('servletContext')
}
static GrailsPluginManager getPluginManager() {
getBean('pluginManager')
}
// For testing
static void registerTestBean(String name, bean) {
TEST_BEANS[name] = bean
}
// For testing
static void unregisterTestBeans() {
TEST_BEANS.clear()
}
}
然后,编辑grails-app/config/spring/resources.groovy
以包括:
applicationContextHolder(ctx.ApplicationContextHolder) { bean ->
bean.factoryMethod = 'getInstance'
}
然后,在你的文件里面src/java
or src/groovy
,你可以调用:
GrailsApplication app = ApplicationContextHolder.getGrailsApplication() ;
ConfigObject config = app.getConfig() ;