【问题标题】:Get spring bean from application context in groovy class从groovy类的应用程序上下文中获取spring bean
【发布时间】:2014-02-14 20:27:17
【问题描述】:

我正在将 grails 应用程序转换为 spring。如何从 spring 'WEB-INF/applicationContext.xml' 获取 groovy 或 java 类中的 spring bean。

这是我用于 grails 应用程序的代码

queueConnectionFactory = (QueueConnectionFactory)Holders.applicationContext.getBean("jmsConnectionFactory");

我试过了

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
queueConnectionFactory usa = (QueueConnectionFactory) ctx.getBean("jmsConnectionFactory");

但它不起作用,我收到一个错误

java.io.FileNotFoundException: 类路径资源 [applicationContext.xml] 无法打开,因为它不存在 在 org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157) 在 org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) 在 org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)

请帮我解决这个问题。谢谢

【问题讨论】:

  • 您的applicationContext.xml 文件是否位于类路径中?如果它在WEB-INF 的根中,我不相信它是。尝试将其移动到源文件夹的根目录。
  • 它在'main/webapps/WEB-INF/applicationContext.xml'目录下。所以它应该可用吧?
  • 我一定会尝试的。顺便说一句,我用来获取 bean 的代码是否正确?感谢您的回复。
  • 抓取 bean 的代码对我来说看起来是正确的,但是您可能想要使用该类。异常明显是找不到配置文件。

标签: java spring grails groovy


【解决方案1】:

尝试将应用程序上下文文件移动到类路径中,例如WEB-INF/classes

【讨论】:

  • 这是永久修复吗? WEB-INF/classes 文件夹不会被下一个构建覆盖或在部署后不可用吗?
  • 很难永久保存,最好将文件放在src/main/resources 中,这样文件在构建后最终会出现在类路径中:)
【解决方案2】:

如果您需要获取单个 bean,则不需要加载整个应用程序上下文。事实上,您可能不想这样做,因为这会在您不需要的上下文中加载其他内容。考虑使用 Spring “aware” 接口,例如 BeanFactoryAwareApplicationContextAware

您想要引用 bean 工厂或上下文的类只需实现这些,例如

public class MyClass implements BeanFactoryAware {

    public void setBeanFactory(BeanFactory factory) {
       // get a reference to the bean factory
    }

    // now in here you can reference the bean factory and lookup the beans

}

【讨论】:

    【解决方案3】:

    我不相信您的applicationContext.xml 文件位于类路径中。尝试将文件放在 source folder 的根目录中,以便将其放在类路径中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-11
      • 2017-02-14
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多