从插件加载应用程序类
在 Grails 1.1 插件中,我尝试使用以下代码从主应用程序加载一个类:
class MyClass {
static Map getCustomConfig(String configName){
return new ConfigSlurper().
parse(ApplicationHolder.application.classLoader.loadClass(configName))
}
}
其中 configName
是 $MAIN_APP/grails-app/conf 中的类的名称
包含配置信息。 但是,当上面的代码在单元测试中运行时,applicationHolder.application
返回 null,导致上面的方法抛出 NullPointerException
。 为此问题创建了 Grails JIRA 问题,但它已被标记为已修复事实上,这个问题似乎仍然存在。
我知道在插件描述符类中,我可以通过隐式 application
变量访问主应用程序(GrailsApplication
的实例)。 但上面显示的代码不在插件描述符中。
有没有办法可以从插件内的主应用程序加载类(但在插件描述符之外)?
谢谢, 大学教师
In a Grails 1.1 plugin, I'm trying to load a class from the main application using the following code:
class MyClass {
static Map getCustomConfig(String configName){
return new ConfigSlurper().
parse(ApplicationHolder.application.classLoader.loadClass(configName))
}
}
Where configName
is the name of the class in $MAIN_APP/grails-app/conf
containing the configuration info. However, when the code above runs within a unit test applicationHolder.application
returns null, causing the method above to throw a NullPointerException
. A Grails JIRA issue was created for this problem, but it has been marked as fixed despite the fact that problem appears to still exist.
I know that within the plugin descriptor class I can access the main application (an instance of GrailsApplication
) via the implicit application
variable. But the code shown above is in not in the plugin descriptor.
Is there a way that I can load a class from the main application within a plugin (but outside the plugin descriptor)?
Thanks,
Don
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实证明有两个可能的答案。
正确答案
GrailsApplication 在单元测试中不可用,因此要使上面的代码正常工作,应该是集成测试
可行的黑客
更改
为
It turns out there are 2 possible answers.
The Right Answer
GrailsApplication is not available in unit tests, so for the code above to work it should be an integration test
The Hack that Works
Change
to