【问题标题】:Spring: why do I need applicationContext.xml when I am using annotations?Spring:为什么我在使用注解时需要 applicationContext.xml?
【发布时间】:2014-06-20 09:48:50
【问题描述】:

我是春季新手

我尝试使用 cargo 在 tomcat 上部署我的 war 文件,它抱怨在目录中找不到 applicationContext.xml

我进一步查看了它应该去哪里并添加了一个空白 xml 文件 applicationContext.xml 以查看它是否有效,但随后它抱怨了一些事情

[INFO] [talledLocalContainer] SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
[INFO] [talledLocalContainer] org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from class path resource [applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.

我不确定我为什么需要applicationContext.xml,如果我真的需要它,我应该在里面放什么?

我尽可能多地使用@annotations,并且我的单元测试也正确通过,意思是,我看到我的 bean 确实连接正确

前辈,请帮忙

谢谢

更新

src/main/webapp/WEB-INF/web.xml

<xml>
</xml>

src/main/resources/applicationContext.xml

<beans></beans>

【问题讨论】:

  • 当你说货物时,你的意思是cargo.codehaus.org/Deploying+to+a+running+container?您还可以展示您的 Java Config 和 web.xml 吗?
  • web.xml 怎么样(或者您使用的是 Servlet 3 初始化程序)?
  • 我的错,我有web.xml 而不是beans.xml。我没有beans.xml
  • 好的,您是否有机会使用WebApplicationInitializerWebMvcConfigurerAdapter?如果是这样,实现/扩展这些的类的内容是什么?

标签: java xml spring spring-mvc annotations


【解决方案1】:

您必须“告诉”您的应用程序在哪里寻找描述您的应用程序上下文的文件,如下所示:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:/applicationContext.xml</param-value>
</context-param>

您可能需要调整&lt;param-value&gt;下的路径,但基本上就是这样。

我还推荐 minimun applicationContext.xml 看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="your.package.here"/>

    <tx:annotation-driven />
</beans>

如果您不需要 Spring 事务管理,请随意删除最后一行和相关架构引用。

我还想提一下,从技术上讲,一种摆脱applicationContext.xml 完全的方法,但我真的怀疑它是否值得。您可能会发现this article 也很有用。

【讨论】:

    【解决方案2】:

    查看参考文档的this part,尤其是这句话:

    侦听器检查 contextConfigLocation 参数。如果参数不存在,则 监听器默认使用 /WEB-INF/applicationContext.xml。

    这将是它在哪里寻找 applicationContext.xml 文件以及原因。

    【讨论】:

      猜你喜欢
      • 2013-08-08
      • 2021-12-09
      • 2017-01-07
      • 2011-09-03
      • 2013-05-29
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      相关资源
      最近更新 更多