Spring, using new ClassPathXmlApplicationContext and getting error being unable to find applicationContext.xml and others?

拈花ヽ惹草 提交于 2020-01-24 13:58:07

问题


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

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();

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


回答1:


Not a direct answer, but here goes.

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.

Instead, you could do something like this to use beanIRPlus bean in your controller.

@Autowired
private BeanIRPlus beanIRPlus;


来源:https://stackoverflow.com/questions/5012636/spring-using-new-classpathxmlapplicationcontext-and-getting-error-being-unable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!