从插件加载应用程序类

发布于 2024-07-20 23:15:48 字数 801 浏览 3 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧人九事 2024-07-27 23:15:48

事实证明有两个可能的答案。

正确答案

GrailsApplication 在单元测试中不可用,因此要使上面的代码正常工作,应该是集成测试

可行的黑客

更改

parse(ApplicationHolder.application.classLoader.loadClass(configName))

parse(MyClass.classLoader.loadClass(configName))

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

parse(ApplicationHolder.application.classLoader.loadClass(configName))

to

parse(MyClass.classLoader.loadClass(configName))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文