【问题标题】:Spring, using new ClassPathXmlApplicationContext and getting error being unable to find applicationContext.xml and others?Spring,使用新的 ClassPathXmlApplicationContext 并得到错误无法找到 applicationContext.xml 和其他?
【发布时间】:2011-02-16 04:52:24
【问题描述】:

我正在尝试按照本教程:http://www.vogella.de/articles/SpringDependencyInjection/article.html 在我的应用程序中使用注解依赖注入。我在教程中设置了 bean 等,然后尝试在我的 MainController 类中获取 bean 的实例(处理为我的 spring web mvc 应用程序生成特定页面的控制器类).. 我不断得到

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 中这样做:

    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 类中,但仍然没有。是否有任何解决方法可以使它不以这种方式搜索路径,因为我认为它在进行相对路径搜索。感谢您的任何建议

【问题讨论】:

    标签: spring dependency-injection annotations


    【解决方案1】:

    不是直接的答案,但这里是。

    您提到的教程是针对独立应用程序而不是 Web 应用程序中的依赖注入。对于 web 应用程序,spring 会自动加载上下文文件并初始化 bean。因此,您不需要MainController 中指定的任何行。

    相反,您可以执行类似的操作来在控制器中使用 beanIRPlus bean。

    @Autowired
    private BeanIRPlus beanIRPlus;
    

    【讨论】:

    • 哇,好大开眼界 :),感谢您的帮助,如果没有那个,我现在就尝试一下.. 如果我需要调用方法,我该如何在 MainController 中实际使用 bean在上面?对此的任何建议/资源表示赞赏,我一直在花费数小时和数小时来查看这方面的内容,但有时会错过重要的事情,比如我刚刚做的事情,因为我还在学习......谢谢
    • 感谢您的所有帮助.. 我以前看过 @Autowired 的东西,但是当刚接触弹簧时,有时很难将 2 和 2 放在一起,因为似乎每个教程都在谈论不同的方式这样做(可能是因为有些是针对非网络的)
    猜你喜欢
    • 2011-01-12
    • 1970-01-01
    • 2011-06-15
    • 2016-10-01
    • 1970-01-01
    • 2013-02-13
    • 2011-03-21
    • 2017-03-10
    • 1970-01-01
    相关资源
    最近更新 更多