简体   繁体   中英

Get spring bean from application context in groovy class

I'm converting a grails application to spring. How to get a spring bean in a groovy or java class from spring 'WEB-INF/applicationContext.xml' .

This was the code I used for grails application

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

I've tried

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

but it didn't work , I was getting an error

java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)

Please help me to resolve this issue . Thanks

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

I do not believe your applicationContext.xml file is located on the classpath. Try placing the file within the root of a source folder so that it is placed on the classpath.

If you need to get a single bean, you shouldn't need to load the entire application context. In fact, you may not want to because that will load up other things in the context that you don't need. Consider using the Spring "aware" interfaces, such as BeanFactoryAware or ApplicationContextAware .

Your class that wants a reference to the bean factory or context just implements these, eg

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM