Spring,使用新的 ClassPathXmlApplicationContext 并出现无法找到 applicationContext.xml 和其他人的错误? [英] Spring, using new ClassPathXmlApplicationContext and getting error being unable to find applicationContext.xml and others?
问题描述
我正在尝试学习本教程:http://www.vogella.de/article/SpringDependencyInjection/article.html 在我的应用程序中使用注解依赖注入.我在教程中设置了 bean 等,然后尝试在我的 MainController 类中获取 bean 的一个实例(一个处理为我的 spring web mvc 应用程序生成特定页面的控制器类).我不断得到 >
I am trying to follow this tutorial: http://www.vogella.de/articles/SpringDependencyInjection/article.html to use annotation dependency injection in my application. I set up the bean, etc like in the tutorial and then am trying to get an instance of the bean within my MainController class (a controller class that handles generating a specific page for my spring web mvc app).. I keep getting
SEVERE: Servlet.service() for servlet spring threw exception
java.io.FileNotFoundException: class path resource [WEB-INF/applicationContext.xml] cannot be opened because it does not exist
我在 MainController 中执行此操作:
I am doing this in my MainController:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BeanFactory factory = context;
BeanIRPlus beanirPlus = (BeanIRPlus) factory
.getBean("BeanIRPlus");
IRPlusInterface irPlus = beanirPlus.getIRPlus();
我对此进行了搜索和搜索,但仍未找到解决我问题的答案.我在 webapp/WEB-INF/中的 applicationContext 和我的 spring 应用程序似乎正在以其他方式工作,因为它在此之前处理请求等.我试过将 applicationContext.xml 放在 WEB-INF 类中,但仍然没有.有什么解决方法可以使它不以这种方式搜索路径,因为我认为它在进行相对路径搜索.感谢您的任何建议
I have searched and searched on this and yet to find an answer that fixes my problem. My applicationContext in in webapp/WEB-INF/ and my spring app seems to be working otherwise as it was handling requests, etc before this. I have tried putting the applicationContext.xml in WEB-INF classes but still nothing. Is there any workaround to make this not search the path this way as I think its doing a relative path search. Thanks for any advice
推荐答案
不是直接的答案,但在这里.
Not a direct answer, but here goes.
您参考的教程是针对独立应用程序而非 Web 应用程序中的依赖项注入的.对于 Web 应用程序,spring 会自动加载上下文文件并初始化 bean.因此,您不需要 MainController
中指定的任何行.
The tutorial you have referred is for dependency injection in a standalone application and not a web application. In case of web application, spring automatically loads the context files and initializes the beans. So you would not need any of the lines specified in the MainController
.
相反,你可以做这样的事情来在你的控制器中使用 beanIRPlus bean.
Instead, you could do something like this to use beanIRPlus bean in your controller.
@Autowired
private BeanIRPlus beanIRPlus;
这篇关于Spring,使用新的 ClassPathXmlApplicationContext 并出现无法找到 applicationContext.xml 和其他人的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!