簡體   English   中英

在Spring Batch中,如何讀取XML屬性?

[英]In Spring Batch, how do I read XML attributes?

我正在嘗試讀取一個XML文件,其中包含具有屬性的元素。 我已經嘗試了多個示例,但是類中的字段始終以null結束,如下所示:

Data [type=null, value=null]
Data [type=null, value=null]
Data [type=null, value=null]

以下是我的問題的簡化示例代碼。

這是位於src / main / resources / data目錄(data.xml)中的XML文件示例:

<?xml version="1.0" encoding="UTF-8"?>
<list>
    <data type="shopping" value="milk" />
    <data type="shopping" value="eggs" />
    <data type="TODO" value="return books to library" />
</list>

以下是我的XML數據(Data.java)域類:

package com.example.demo.springbatchtest.domain;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "data")
public class Data {
    private final String type;
    private final String value;

    public Data(String type, String value) {
        this.type = type;
        this.value = value;
    }

    @XmlAttribute(name = "type")
    public String getType() {
        return type;
    }

    @XmlAttribute(name = "value")
    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return "Data [type=" + type + ", value=" + value + "]";
    }

}

這是我的Spring Batch作業配置文件(JobConfiguration.java):

package com.example.demo.springbatchtest.configuration;

import java.util.HashMap;
import java.util.Map;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.xml.StaxEventItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.xstream.XStreamMarshaller;

import com.example.demo.springbatchtest.domain.Data;

@Configuration
public class JobConfiguration {
    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    StepBuilderFactory stepBuilderFactory;

    @Bean
    public StaxEventItemReader<Data> dataItemReader() {
        XStreamMarshaller unmarshaller = new XStreamMarshaller();

        Map<String, Class> aliases = new HashMap<>();
        aliases.put("data", Data.class);

        unmarshaller.setAliases(aliases);

        StaxEventItemReader<Data> reader = new StaxEventItemReader<>();

        reader.setResource(new ClassPathResource("/data/data.xml"));

        reader.setFragmentRootElementName("data");
        reader.setUnmarshaller(unmarshaller);

        return reader;
    }

    @Bean
    public ItemWriter<Data> dataItemWriter() {
        return items -> {
            for (Data item : items) {
                System.out.println(item.toString());
            }
        };
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .<Data, Data>chunk(10)
                .reader(dataItemReader())
                .writer(dataItemWriter())
                .build();
    }

    @Bean
    public Job job() {
        return jobBuilderFactory
                .get("job")
                .start(step1())
                .build();
    }

}

這是我的主要Spring Boot類(SpringBatchTestApplication.java):

package com.example.demo.springbatchtest;

import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableBatchProcessing
public class SpringBatchTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBatchTestApplication.class, args);
    }
}

這是我的pom.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<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.example</groupId>
    <artifactId>SpringBatchTestSpringBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringBatchTestSpringBoot</name>
    <description>Spring Batch Test with Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

聽起來JAX-B無法設置Data.type和value屬性。

默認情況下,它將為每個屬性尋找一個getter / setter對,否則它們將被視為只讀。

另一種方法是使用字段級別的訪問權限-@XmlAccessorType(XmlAccessType.FIELD)

找到了本教程,它幫助我獲得了示例代碼。

https://walkingtechie.blogspot.com/2017/03/spring-batch-xml-file-to-mysql-example.html

關鍵是使用Converter類解析屬性。 因此,在我的示例中,我在JobConfiguration類的dataItemReader()中添加了一個調用集Converter類。

import com.example.demo.springbatchtest.converter.DataConverter;

...

@Autowired
private DataConverter dataConverter;

...

@Bean
public StaxEventItemReader<Data> dataItemReader() {
    XStreamMarshaller unmarshaller = new XStreamMarshaller();

    Map<String, Class> aliases = new HashMap<>();
    aliases.put("data", Data.class);

    unmarshaller.setAliases(aliases);
    unmarshaller.setConverters(dataConverter);  // from Walking Techie

    StaxEventItemReader<Data> reader = new StaxEventItemReader<>();

    reader.setResource(new ClassPathResource("/data/data.xml"));

    reader.setFragmentRootElementName("data");
    reader.setUnmarshaller(unmarshaller);

    return reader;
}

然后,我擴展了Converter類以處理屬性。

package com.example.demo.springbatchtest.converter;

import org.springframework.stereotype.Component;

import com.example.demo.springbatchtest.domain.Data;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

@Component
public class DataConverter implements Converter {

  @Override
  public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {

  }

  @Override
  public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    String type = reader.getAttribute("type");
    String value = reader.getAttribute("value");

    return new Data(type, value);
  }


  @Override
  public boolean canConvert(Class type) {
    return type.equals(Data.class);
  }
}

程序現在輸出以下內容:

Data [type=shopping, value=milk]
Data [type=shopping, value=eggs]
Data [type=TODO, value=return books to library]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM