[英]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.