it-swarm-pt.tech

Não foi possível localizar o namespace do Spring NamespaceHandler para o esquema XML [http://www.springframework.org/schema/batch]

Situação

Estou usando o Spring Batch para criar um Instantâneo Acumulativo para nosso Data Warehouse e estou tendo um roadblock de configuração que não consigo descobrir.

Criei um Projeto de Lote de Primavera Simples com STS (SpringSource Tool Suite 2.8.1) usando o Projeto de Modelo de Primavera . Estes foram meus dois arquivos de configuração xml criados:

launch-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
    http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:property-placeholder location="classpath:batch.properties" />

<context:component-scan base-package="edu.kdc.visioncards" />

<jdbc:initialize-database data-source="dataSource">
    <jdbc:script location="${batch.schema.script}" />
</jdbc:initialize-database>

<batch:job-repository id="jobRepository" />

<import resource="classpath:/META-INF/spring/module-context.xml" />

e module-context.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:batch="http://www.springframework.org/schema/batch"
xsi:schemaLocation="http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<description>Example job to get you started. It provides a skeleton for a typical batch application.</description>

<batch:job id="job1">
    <batch:step id="step1"  >           
        <batch:tasklet transaction-manager="transactionManager" start-limit="100" >
            <batch:chunk reader="reader" writer="writer" commit-interval="1" />
        </batch:tasklet>
    </batch:step>
</batch:job> 

</beans>

Problema

Executo o seguinte comando para compilar e empacotar o projeto: mvn clean compile install

então faço o seguinte:

  1. cd para pasta de destino

  2. Execute o trabalho por meio de CommandLineJobRunner: Java -jar batchprimer-1.0.jar META-INF/spring/module-context.xml job1

e recebo o seguinte erro:

C:\stsworkspace\BatchPrimer\target>Java -jar batchprimer-1.0.jar META-INF/spring
/module-context.xml job1
2011-12-15 12:03:53,421 INFO [org.springframework.context.support.ClassPathXmlAp
plicationContext] - <Refreshing org.springframework.context.support.ClassPathXml
[email protected]: startup date [Thu Dec 15 12:03:53 EST 2011]; root of
context hierarchy>
2011-12-15 12:03:53,468 INFO [org.springframework.beans.factory.xml.XmlBeanDefin
itionReader] - <Loading XML bean definitions from class path resource [META-INF/
spring/module-context.xml]>
2011-12-15 12:03:53,796 ERROR [org.springframework.batch.core.launch.support.Com
mandLineJobRunner] - <Job Terminated in error: Configuration problem: Unable to
locate Spring NamespaceHandler for XML schema namespace [http://www.springframew
ork.org/schema/batch]
Offending resource: class path resource [META-INF/spring/module-context.xml]
>
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Config
uration problem: Unable to locate Spring NamespaceHandler for XML schema namespa
ce [http://www.springframework.org/schema/batch]
Offending resource: class path resource [META-INF/spring/module-context.xml]

        at org.springframework.beans.factory.parsing.FailFastProblemReporter.err
or(FailFastProblemReporter.Java:68)
        at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderC
ontext.Java:85)
        at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderC
ontext.Java:80)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.er
ror(BeanDefinitionParserDelegate.Java:284)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.pa
rseCustomElement(BeanDefinitionParserDelegate.Java:1335)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.pa
rseCustomElement(BeanDefinitionParserDelegate.Java:1328)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe
ader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.Java:135)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe
ader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.Java:93)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registe
rBeanDefinitions(XmlBeanDefinitionReader.Java:493)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadB
eanDefinitions(XmlBeanDefinitionReader.Java:390)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBea
nDefinitions(XmlBeanDefinitionReader.Java:334)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBea
nDefinitions(XmlBeanDefinitionReader.Java:302)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReade
r.loadBeanDefinitions(AbstractBeanDefinitionReader.Java:143)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReade
r.loadBeanDefinitions(AbstractBeanDefinitionReader.Java:178)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReade
r.loadBeanDefinitions(AbstractBeanDefinitionReader.Java:149)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReade
r.loadBeanDefinitions(AbstractBeanDefinitionReader.Java:212)
        at org.springframework.context.support.AbstractXmlApplicationContext.loa
dBeanDefinitions(AbstractXmlApplicationContext.Java:126)
        at org.springframework.context.support.AbstractXmlApplicationContext.loa
dBeanDefinitions(AbstractXmlApplicationContext.Java:92)
        at org.springframework.context.support.AbstractRefreshableApplicationCon
text.refreshBeanFactory(AbstractRefreshableApplicationContext.Java:130)
        at org.springframework.context.support.AbstractApplicationContext.obtain
FreshBeanFactory(AbstractApplicationContext.Java:467)
        at org.springframework.context.support.AbstractApplicationContext.refres
h(AbstractApplicationContext.Java:397)
        at org.springframework.context.support.ClassPathXmlApplicationContext.<i
nit>(ClassPathXmlApplicationContext.Java:139)
        at org.springframework.context.support.ClassPathXmlApplicationContext.<i
nit>(ClassPathXmlApplicationContext.Java:83)
        at org.springframework.batch.core.launch.support.CommandLineJobRunner.st
art(CommandLineJobRunner.Java:282)
        at org.springframework.batch.core.launch.support.CommandLineJobRunner.ma
in(CommandLineJobRunner.Java:574)

Coisas adicionais

Na pasta de destino que foi preenchida com o comando mvn install, tenho o seguinte:

  1. Pasta A classes
  2. uma pasta lib com todas as minhas dependências
  3. uma pasta maven-archiver
  4. uma pasta classes de teste
  5. a batchprimer-1.0.jar

Dentro do jarro, no META-INF/MANIFEST.MF . Eu tenho o seguinte:

Manifest-Version: 1.0

Archiver-Version: Plexus Archiver

Created-By: Apache Maven

Built-By: dpardo

Build-Jdk: 1.6.0_20

Main-Class: org.springframework.batch.core.launch.support.CommandLineJ
 obRunner

Class-Path: lib/spring-jdbc-3.0.6.RELEASE.jar lib/spring-beans-3.0.6.R
 ELEASE.jar lib/spring-core-3.0.6.RELEASE.jar lib/spring-asm-3.0.6.REL
 EASE.jar lib/commons-logging-1.1.1.jar lib/spring-tx-3.0.6.RELEASE.ja
 r lib/aopalliance-1.0.jar lib/spring-aop-3.0.6.RELEASE.jar lib/spring
 -context-3.0.6.RELEASE.jar lib/spring-expression-3.0.6.RELEASE.jar li
 b/cglib-nodep-2.2.jar lib/spring-batch-core-2.1.7.RELEASE.jar lib/spr
 ing-batch-infrastructure-2.1.7.RELEASE.jar lib/xstream-1.3.jar lib/xp
 p3_min-1.1.4c.jar lib/jettison-1.1.jar lib/commons-io-1.4.jar lib/com
 mons-dbcp-1.2.2.jar lib/commons-pool-1.3.jar lib/hsqldb-1.8.0.7.jar l
 ib/aspectjrt-1.6.8.jar lib/aspectjweaver-1.6.8.jar lib/log4j-1.2.14.j
 ar lib/slf4j-log4j12-1.5.8.jar lib/slf4j-api-1.5.8.jar lib/mysql-conn
 ector-Java-5.1.3.jar

Portanto, não acho que seja um problema de caminho de classe porque no console parece que ele está encontrando os jarros.

O que eu tentei

Com base no erro, colei o seguinte URL

http://www.springframework.org/schema/batch/

e o endereço dos espaços para nome do Spring Batch parece estar correto. Eu não encontrei nada útil nem lá fora. Li em algum lugar que "algo" poderia estar substituindo os espaços para nome dos arquivos, mas realmente não entendi o porquê, o que e/ou como resolvê-lo.

Isso já está pronto e já não está funcionando sem ter feito modificações, complementos ou qualquer coisa. Alguma ideia?

Obrigado

SOLUÇÃO

Além do marcado como solução correta abaixo. Também tive que alterar o launch-context.xml da varredura de componentes para a fiação regular da mola como esta abaixo:

<!-- Commented this 
<context:property-placeholder location="classpath:batch.properties" />  


<jdbc:initialize-database data-source="dataSource">
    <jdbc:script location="${batch.schema.script}" />
</jdbc:initialize-database>
-->
<!-- Replace it with this below -->
<bean id="dataSource" class="org.Apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${batch.jdbc.driver}" />
    <property name="url" value="${batch.jdbc.url}" />
    <property name="username" value="${batch.jdbc.user}" />
    <property name="password" value="${batch.jdbc.password}" />
</bean>

<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
    lazy-init="true">
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="placeholderProperties"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:batch.properties" />
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="order" value="1" />
</bean>
12
Viriato

Execute o trabalho por meio de CommandLineJobRunner: Java -jar batchprimer-1.0.jar META-INF/spring/module-context.xml job1

, mesmo com uma pasta de destino completa, você deve fornecer as informações do caminho de classe para o Java comando , para facilitar a configuração pode experimentá-lo com um jar executável completo, por exemplo, com maven-shade-plugin ou um script executável do Shell (.bat/.sh) com todas as bibliotecas necessárias, por exemplo, com appassembler -maven-plugin

exemplo de configuração do maven-shade-plugin (cria jar adicional):

<plugin>
    <!-- create an all-in-one executable jar with maven-shade-plugin
         bound to phase:package 
         special handling for spring.handlers/spring.schemas files
         to prevent overwriting (maven-shade-plugin joins them to
         one file) 

         usage:
         cd to <project>/target
         Java -jar hello-world-Java-1.0-SNAPSHOT-executable.jar spring/batch/job/hello-world-job.xml helloWorldJob
         -->                     
    <artifactId>maven-shade-plugin</artifactId>
    <version>1.5</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer implementation="org.Apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>org.springframework.batch.core.launch.support.CommandLineJobRunner</mainClass>
                    </transformer>
                    <transformer implementation="org.Apache.maven.plugins.shade.resource.AppendingTransformer">
                        <resource>META-INF/spring.handlers</resource>
                    </transformer>
                    <transformer implementation="org.Apache.maven.plugins.shade.resource.AppendingTransformer">
                        <resource>META-INF/spring.schemas</resource>
                    </transformer>
                </transformers>
                <shadedArtifactAttached>true</shadedArtifactAttached>
                <!-- configures the suffix name for the executable jar
                     here it will be '<project.artifact>-<project.version>-executable.jar'-->
                <shadedClassifierName>executable</shadedClassifierName>
            </configuration>
        </execution>
    </executions>
</plugin>

exemplo de configuração do appassembler (cria estrutura de subpastas e .bat/.sh):

<plugin>
    <artifactId>appassembler-maven-plugin</artifactId>
    <groupId>org.codehaus.mojo</groupId>
    <version>1.1.1</version>
    <configuration>
        <repositoryLayout>flat</repositoryLayout>
        <installArtifacts>false</installArtifacts>
        <target>${project.build.directory}/appassembler</target>
        <defaultJvmSettings>
            <initialMemorySize>512M</initialMemorySize>
            <maxMemorySize>1024M</maxMemorySize>
            <extraArguments>
                <extraArgument>-Dlog4j.configuration=../etc/log4j/log4j.properties</extraArgument>
            </extraArguments>
        </defaultJvmSettings>
        <configurationDirectory>etc</configurationDirectory>
        <daemons>
            <daemon>
                <id>applicationName</id>
                <mainClass>org.springframework.batch.core.launch.support.CommandLineJobRunner</mainClass>
                <commandLineArguments>
                    <commandLineArgument>spring/job-runner.xml</commandLineArgument>
                    <commandLineArgument>helloWorldJob</commandLineArgument>
                    <commandLineArgument>input.file.pattern=file:.../**/*.txt</commandLineArgument>
                </commandLineArguments>
                <platforms>
                    <platform>booter-unix</platform>
                    <platform>booter-windows</platform>
                </platforms>
            </daemon>
        </daemons>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>generate-daemons</goal>
                <goal>create-repository</goal>
            </goals>
        </execution>
    </executions>
</plugin>
28
Michael Pralow

Eu estava usando o lote de primavera versão 3.X.X e outras dependências de primavera versões 4.X.X e recebi o erro acima. Após algumas tentativas e erros, descobri que manter todas as versões semelhantes da primavera corrigia meu problema. Portanto, sugiro que você use a versão 3.X.X do lote de primavera ou faça a versão dependente da primavera para spring-jdbc e spring-tx para 2.X.X

Atenciosamente, Rave

1
Ravikiran butti

Você precisa do spring-batch.jar no caminho de classe do tempo de execução. Ele fornece um manipulador de namespace capaz de lidar com esse namespace específico.

0
Bozho

O erro foi causado porque o arquivo META-INF/spring.handlers no spring-batch-core-2.1.7.RELEASE.jar não está sendo visto. Este arquivo contém

http\://www.springframework.org/schema/batch=org.springframework.batch.core.configuration.xml.CoreNamespaceHandler

Parece um problema do caminho de classe ou como o arquivo spring.handlers nos outros JARs (contexto da primavera, por exemplo), de alguma forma, tem precedência.

0
Emerson Farrugia

No meu caso, estava simplesmente faltando a dependência da transação da primavera - ou talvez apontando para uma antiga. Substituir isso por 3.1 levou o erro.

0
Albert Mendonca