2014-05-18 3 views
0

Я использую Spring - Maven - Eclipse, и я столкнулся с этим уродливым исключением относительно инициализации контекста. Он отлично работает, когда я помещаю файлы конфигураций в WEB-INF, но я читал, что их рекомендуется поместить в папку src/main/resources. В этот момент возникает исключение.Ошибка инициализации контекста Spring Maven

Я потратил несколько часов, пытаясь решить это самостоятельно, но я не увенчался успехом. Что случилось с моей конфигурацией?

Благодарим за помощь.

Stack следы

Severe: Context initialization failed  org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/controller-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/controller-servlet.xml] 
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) 
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) 
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174) 
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209) 
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) 
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) 
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94) 
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131) 
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537) 
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451) 
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:647) 
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598) 
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661) 
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517) 
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458) 
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138) 
at javax.servlet.GenericServlet.init(GenericServlet.java:244) 
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1444) 
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1241) 
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5093) 
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5380) 
at com.sun.enterprise.web.WebModule.start(WebModule.java:498) 
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:917) 
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:901) 
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:733) 
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2000) 
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1651) 
at com.sun.enterprise.web.WebApplication.start(WebApplication.java:109) 
at org.glassfish.internal.data.EngineRef.start(EngineRef.java:130) 
at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:269) 
at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:294) 
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:462) 
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240) 
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:382) 
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355) 
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:370) 
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1064) 
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:96) 
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1244) 
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1232) 
at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:129) 
at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:105) 
at org.glassfish.maven.PluginUtil.doDeploy(PluginUtil.java:106) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:606) 
at org.glassfish.maven.AbstractDeployMojo.doDeploy(AbstractDeployMojo.java:239) 
at org.glassfish.maven.RunMojo.execute(RunMojo.java:68) 
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:107) 
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209) 
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) 
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) 
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) 
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) 
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) 
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) 
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319) 
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156) 
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:534) 
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196) 
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:606) 
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290) 
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230) 
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409) 
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352) 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven- 4.0.0.xsd"> 
<modelVersion>4.0.0</modelVersion> 
<groupId>com.marc</groupId> 
<artifactId>embedded-glassfish-test</artifactId> 
<version>0.0.2-SNAPSHOT</version> 
<packaging>war</packaging> 
<properties> 
    <java-version>1.7</java-version> 
    <org.springframework-version>3.2.0.RELEASE</org.springframework-version> 
    <embedded-glassfish-version>3.1.1</embedded-glassfish-version> 
    <eclipselink-version>2.5.1</eclipselink-version> 
    <javax-persistence-version>2.1.0</javax-persistence-version> 
    <org.slf4j-version>1.5.11</org.slf4j-version> 
    <spring-test-version>3.2.0.RELEASE</spring-test-version> 
    <derby-version>10.10.1.1</derby-version> 
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
</properties> 
<dependenc 
    <!-- Logging --> 
    <dependency> 
     <groupId>org.slf4j</groupId> 
     <artifactId>slf4j-api</artifactId> 
     <version>${org.slf4j-version}</version> 
    </dependency> 
    <dependency> 
     <groupId>org.slf4j</groupId> 
     <artifactId>slf4j-log4j12</artifactId> 
     <version>${org.slf4j-version}</version> 
     <scope>runtime</scope> 
    </dependency> 
<!-- slf4j-bridge for commons-logging --> 
    <dependency> 
     <groupId>org.slf4j</groupId> 
     <artifactId>jcl-over-slf4j</artifactId> 
     <version>${org.slf4j-version}</version> 
    </dependency> 
    <!-- Spring --> 
    <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-webmvc</artifactId> 
     <version>${org.springframework-version}</version> 
        <exclusions> 
      <!-- Exclude Commons Logging in favor of SLF4j --> 
      <exclusion> 
       <groupId>commons-logging</groupId> 
       <artifactId>commons-logging</artifactId> 
      </exclusion> 
     </exclusions> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-context</artifactId> 
     <version>${org.springframework-version}</version> 
     <exclusions> 
      <!-- Exclude Commons Logging in favor of SLF4j --> 
      <exclusion> 
       <groupId>commons-logging</groupId> 
       <artifactId>commons-logging</artifactId> 
      </exclusion> 
     </exclusions> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-core</artifactId> 
     <version>${org.springframework-version}</version> 
    </dependency> 
    <!-- **************************************************************************************************** --> 
    <dependency> 
     <groupId>javax.servlet</groupId> 
     <artifactId>jstl</artifactId> 
     <version>1.2</version> 
    </dependency> 
    <dependency> 
     <groupId>javax.servlet</groupId> 
     <artifactId>servlet-api</artifactId> 
     <version>2.5</version> 
     <scope>test</scope> 
    </dependency> 
    <!-- @Inject --> 
    <dependency> 
     <groupId>javax.inject</groupId> 
     <artifactId>javax.inject</artifactId> 
     <version>1</version> 
    </dependency> 
    <!-- JDBC --> 
    <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-jdbc</artifactId> 
     <version>${org.springframework-version}</version> 
    </dependency> 
    <!-- glassfish -->  
    <dependency> 
     <groupId>org.glassfish</groupId> 
     <artifactId>maven-embedded-glassfish-plugin</artifactId> 
     <version>${embedded-glassfish-version}</version> 
     <type>maven-plugin</type> 
    </dependency> 
    <!-- eclipselink --> 
    <dependency> 
     <groupId>org.eclipse.persistence</groupId> 
     <artifactId>eclipselink</artifactId> 
     <version>${eclipselink-version}</version> 
     <scope>provided</scope> 
    </dependency> 
    <dependency> 
     <groupId>org.eclipse.persistence</groupId> 
     <artifactId>javax.persistence</artifactId> 
     <version>${javax-persistence-version}</version> 
     <scope>provided</scope> 
    </dependency> 
    <!-- spring jpa --> 
    <dependency> 
     <groupId>org.springframework.data</groupId> 
     <artifactId>spring-data-jpa</artifactId> 
     <version>1.4.2.RELEASE</version> 
     <exclusions> 
      <exclusion> 
       <artifactId>slf4j-api</artifactId> 
       <groupId>org.slf4j</groupId> 
      </exclusion> 
     </exclusions> 
    </dependency> 
    <!-- spring test --> 
    <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-test</artifactId> 
     <version>${spring-test-version}</version> 
     <scope>test</scope> 
    </dependency> 
    <!-- junit --> 
    <dependency> 
     <groupId>junit</groupId> 
     <artifactId>junit</artifactId> 
     <version>4.11</version> 
    </dependency> 
    <!-- derby --> 
    <dependency> 
     <groupId>org.apache.derby</groupId> 
     <artifactId>derby</artifactId> 
     <version>${derby-version}</version> 
     <scope>compile</scope> 
    </dependency> 
</dependencies> 
    <!-- embedded glassfish plugin --> 
<build> 
    <plugins> 
     <plugin> 
      <groupId>org.glassfish</groupId> 
      <artifactId>maven-embedded-glassfish-plugin</artifactId> 
      <version>${embedded-glassfish-version}</version> 
      <configuration> 
       <ports> 
        <http-listener>8080</http-listener> 
        <https-listener>8181</https-listener> 
       </ports> 
       <contextRoot>${project.artifactId}</contextRoot> 
      </configuration> 
      <dependencies> 
       <dependency> 
        <groupId>mysql</groupId> 
        <artifactId>mysql-connector-java</artifactId> 
        <version>5.1.27</version> 
       </dependency> 
      </dependencies> 
     </plugin> 
     <plugin> 
      <artifactId>maven-compiler-plugin</artifactId> 
      <version>3.1</version> 
      <configuration> 
       <source>${java-version}</source> 
       <target>${java-version}</target> 
       <testSource>${java-version}</testSource> 
       <testTarget>${java-version}</testTarget>  
       <encoding>${project.build.sourceEncoding}</encoding> 
      </configuration> 
     </plugin> 
    </plugins> 
</build>  

WEB-INF/web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
    version="3.0"> 

<display-name>Spring Web MVC Application</display-name> 

<servlet> 
    <servlet-name>controller</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <load-on-startup>1</load-on-startup> 
</servlet> 
<servlet-mapping> 
    <servlet-name>controller</servlet-name> 
    <url-pattern>/</url-pattern> 
</servlet-mapping> 

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>classpath:controller-servlet.xml 
       classpath:controller-persistence.xml 
    </param-value> 
</context-param> 

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 
<!-- database jndi reference --> 
<description>MySQL Test App</description> 
<resource-ref> 
    <description>DB Connection</description> 
    <res-ref-name>jdbc/TestDB</res-ref-name> 
    <res-type>javax.sql.DataSource</res-type> 
    <res-auth>Container</res-auth> 
</resource-ref> 

<persistence-unit-ref> 
     <persistence-unit-ref-name>jdbc/derby</persistence-unit-ref-name>  
     <persistence-unit-name>derby</persistence-unit-name> 
</persistence-unit-ref> 

SRC/основные/ресурсы

  • Контроллер-servlet.xml
  • Контроллер-persistence.xml
+0

Servlet контекст (* Контроллер-servlet.xml *) ** ДОЛЖНЫ ** под WEB-INF. Только корневые файлы контекста должны быть в пути к классам (т. Е. 'Src/main/resources'). У вас также есть вторая ошибка в контексте 'web.xml' - сервлета ** НЕ ДОЛЖНА ** быть определена как корневой контекст config (т.е. удалить его из' contextConfigLocation') ... этот файл будет автоматически загружен 'DispatcherServlet '(по умолчанию он ищет конфигурацию в'/WEB-INF/{servletName} -servlet.xml'). –

+0

Попробуйте прочитать что-то о иерархии контекстов, используемой Spring - например. http://stackoverflow.com/questions/3652090/difference-between-applicationcontext-xml-and-spring-servlet-xml-in-spring –

+0

@Pavel: Спасибо, но мне это непонятно. Для меня controller-servlet.xml и controller-persistence.xml являются корневыми файлами контекста. Следовательно, они должны быть в src/main/resources. Например: https: // github.com/pkainulainen/spring-mvc-test-examples/tree/master/controller/src/main/resources Можно видеть, что он размещает то, что я называю конфигурационными файлами в src/main/resources. Он является автором книги «Весенние данные». – user3178994

ответ

0

Ошибка очень четко (выделено мин):

Жесткий: Ошибка инициализации контекста org.springframework.beans.factory.BeanDefinitionStoreException: IOException синтаксический анализ XML-документа из ресурса ServletContext [/WEB-INF/controller-servlet.xml]; вложенное исключение java.io.FileNotFoundException: Не удалось открыть ServletContext ресурс [/WEB-INF/controller-servlet.xml]

Переместить файл контроллера servlet.xml в папку WEB-INF.

Подробнее:

+0

Спасибо, Луиджи, но я прочитал много статей, в которых говорится, что рекомендуется размещать файлы конфигурации в src/main/resources, и многие люди говорят, что это работает как charme ...!? – user3178994

+0

@ user3178994 и вот как вам нужно работать, кроме основного файла конфигурации приложения xml для веб-приложения. –

+1

@ user3178994 В игре есть два разных контекста: контекст корневого веб-приложения (загружается ContextLoaderListener) и контекст приложения сервлета (загружается DispatcherServlet). Последний ДОЛЖЕН находиться под '/ WEB-INF/{servletName} -servlet.xml'. Проверить JavaDoc - http://docs.spring.io/spring-framework/docs/4.0.x/javadoc-api/org/springframework/web/servlet/FrameworkServlet.html –

Смежные вопросы