[英]Get spring bean from application context in groovy class
我正在将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.beans.factory的org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157)中不存在。 org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)中的xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
请帮我解决这个问题。 谢谢
尝试将应用程序上下文文件移动到类路径上,例如WEB-INF/classes
我不相信您的applicationContext.xml
文件位于类路径上。 尝试将文件放在source folder
的根目录中,以便将其放在类路径中。
如果需要获取单个bean,则不需要加载整个应用程序上下文。 实际上,您可能不想这样做,因为这会在您不需要的上下文中加载其他内容。 考虑使用Spring“感知”接口,例如BeanFactoryAware或ApplicationContextAware 。
您想要引用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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.